Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

Auto Generate Create Table Script Based on SQL Server Query

$
0
0

By: Daniel Farina || Related Tips:More > Functions - User Defined UDF

Problem

You have to create a SQL Server table to store the results from a query. At first you think about looking at each column data type to create the table, but realize it will be a tedious task. In this tip we look at a function you can use to generate a create table script that has the correct data types for each column based on the source columns.

Solution

We as SQL Server database professionals write queries each day and some circumstances we need the query to store the data in a table so we can do further analysis or we need to get the data from the query from different sources into one common table. In such case, we can’t use a SELECT INTO statement to create the destination table. This is especially important in case we are working inside a stored procedure that uses a temporary table that needs to be populated with a SELECT statement twice.

For the purposes of this tip, I will use the query from my previous tip Create SQL Server Disk Space Report for All Servers as an example.

T-SQL Script to Generate a Table based on a Query

During the course of this tip we will go through the process of creating a scalar function that takes a SELECT statement as a parameter and returns the CREATE TABLE script for the query, so you can pass it as a parameter to an EXEC or sp_executesql statement.

In order to achieve this, we will be using the Dynamic Management Function sys.dm_exec_describe_first_result_set.

The DMF sys.dm_exec_describe_first_result_set was introduced in SQL Server 2012. This function has the following parameters: @tsql, @params and @browse_information_mode. The table below has the descriptions of the parameters as found at the following Microsoft help link .

Parameter Description tsql The Transact SQL script or batch. params It provides a declaration string for parameters for the Transact-SQL batch, which is similar to sp_executesql. Parameters may be nvarchar(n) or nvarchar(max). browse_information_mode Specifies if additional key columns and source table information are returned. If set to 1, each query is analyzed as if it includes a FOR BROWSE option on the query. Additional key columns and source table information are returned. If set to 0, no information is returned. If set to 1, each query is analyzed as if it includes a FOR BROWSE option on the query. This will return base table names as the source column information. If set to 2, each query is analyzed as if it would be used in preparing or executing a cursor. This will return view names as source column information.

Let’s run a SELECT statement using this function and using the query from this tip Create SQL Server Disk Space Report for All Servers . Note, I had to make all single quotes into double single quotes since the query is passed as a parameter.

USE AdventureWorks2012
GO
SELECT * FROM sys.dm_exec_describe_first_result_set ('
SELECT @@SERVERNAME [Server] ,
DB_NAME() [Database] ,
MF.name [File Name] ,
MF.type_desc [Type] ,
MF.physical_name [Path] ,
CAST(CAST(MF.size / 128.0 AS DECIMAL(15, 2)) AS VARCHAR(50)) + '' MB'' [File Size] ,
CAST(CONVERT(DECIMAL(10, 2), MF.size / 128.0 - ( ( size / 128.0 ) - CAST(FILEPROPERTY(MF.name, ''SPACEUSED'') AS INT) / 128.0 )) AS VARCHAR(50)) + '' MB'' [File Used Space] ,
CAST(CONVERT(DECIMAL(10, 2), MF.size / 128.0 - CAST(FILEPROPERTY(MF.name, ''SPACEUSED'') AS INT) / 128.0) AS VARCHAR(50)) + '' MB'' [File Free Space] ,
CAST(CONVERT(DECIMAL(10, 2), ( ( MF.size / 128.0 - CAST(FILEPROPERTY(MF.name, ''SPACEUSED'') AS INT) / 128.0 ) / ( MF.size / 128.0 ) ) * 100) AS VARCHAR(50)) + ''%'' [% Free File Space] ,
IIF(MF.growth = 0, ''N/A'',
CASE WHEN MF.is_percent_growth = 1 THEN CAST(MF.growth AS VARCHAR(50)) + ''%''
ELSE CAST(MF.growth / 128 AS VARCHAR(50)) + '' MB''
END) [Autogrowth] ,
VS.volume_mount_point ,
CAST(CAST(VS.total_bytes / 1024. / 1024 / 1024 AS DECIMAL(20, 2)) AS VARCHAR(50)) + '' GB'' [Total Volume Size] ,
CAST(CAST(VS.available_bytes / 1024. / 1024 / 1024 AS DECIMAL(20, 2)) AS VARCHAR(50)) + '' GB'' [Free Space] ,
CAST(CAST(VS.available_bytes / CAST(VS.total_bytes AS DECIMAL(20, 2)) * 100 AS DECIMAL(20, 2)) AS VARCHAR(50)) + ''%'' [% Free]
FROM sys.database_files MF
CROSS APPLY sys.dm_os_volume_stats(DB_ID(''?''), MF.file_id) VS',NULL, null)

As you can see in the next screen capture, the output of this function is a table that contains a detailed description of each column of the query that we provided as the parameter.


Auto Generate Create Table Script Based on SQL Server Query

In the next table you will see a description of each output column. You can see the full table at this link .

For our purposes we will only use the following columns: name, is_nullable, system_type_name, collation_name and is_hidden to filter because we don’t want columns than don’t appear in the result set.

Column Description is_hidden Specifies that the column is an extra column added for browsing and informational purposes that does not actually appear in the result set. column_ordinal Contains the ordinal position of the column in the result set. Position of the first column will be specified as 1. name Contains the name of the column if a name can be determined. If not, will contain NULL. is_nullable Contains the following values: Value 1 if column allows NULLs. Value 0 if the column does not allow NULLs. Value 1 if it cannot be determined that the column allows NULLs. system_type_id Contains the system_type_id of the column data type as specified in sys.types. For CLR types, even though the system_type_name column will return NULL, this column will return the value 240. system_type_name Contains the name and arguments (such as length, precision, scale), specified for the data type of the column. If data type is a user-defined alias type, the underlying system type is specified here. If data type is a CLR user-defined type, NULL is returned in this column. max_length Maximum length (in bytes) of the column. -1 = Column data type is varchar(max), nvarchar(max), varbinary(max), or x

Viewing all articles
Browse latest Browse all 3160

Latest Images

Trending Articles