forked from ktaranov/sqlserver-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerate_table_definition_to_match_query.sql
More file actions
27 lines (23 loc) · 1.06 KB
/
Generate_table_definition_to_match_query.sql
File metadata and controls
27 lines (23 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
Created: 2017-08-21 by SQL Undercover
Modified: 2019-03-26 by Konstantin Taranov
Original link: https://sqlundercover.com/2017/08/21/undercover-toolbox-generate-a-temporary-table-definition-to-match-the-resultset-of-a-query/
Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Generate_table_definition_to_match_query.sql
*/
SET NOCOUNT ON;
DECLARE @Query VARCHAR(MAX) = 'select * from sys.databases;';
DECLARE @TempTableName VARCHAR(128) = '#temptable';
DECLARE @ColumnList VARCHAR(MAX);
SELECT @ColumnList = STUFF(
(SELECT ' , ' + name + ' ' + system_type_name + ' ' +
CASE is_nullable
WHEN 0 THEN 'NOT NULL'
ELSE 'NULL'
END + CHAR(10)
FROM sys.dm_exec_describe_first_result_set(@Query, NULL, 0)
FOR XML PATH('')
)
,1 ,1, '');
PRINT 'CREATE TABLE ' + @TempTableName + '('
PRINT @ColumnList;
PRINT(');');