Created
July 30, 2013 21:48
-
-
Save billinkc/6117311 to your computer and use it in GitHub Desktop.
Quick and dirty way to generate insert statements against self
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE | |
@schema sysname = 'DW' | |
, @tableName sysname = 'DimDate' | |
DECLARE | |
@Header nvarchar(max) = N'INSERT INTO ' + QUOTENAME(@schema) + '.' + QUOTENAME(@tableName) | |
, @Body nvarchar(max) = N''; | |
WITH SRC AS | |
( | |
SELECT | |
QUOTENAME(ISC.COLUMN_NAME) AS COLUMN_NAME | |
, ISC.TABLE_NAME | |
, ISC.TABLE_SCHEMA | |
FROM | |
INFORMATION_SCHEMA.COLUMNS ISC | |
WHERE | |
ISC.TABLE_SCHEMA = @schema | |
AND ISC.TABLE_NAME = @tableName | |
) | |
, S2 AS | |
( | |
SELECT DISTINCT | |
QUOTENAME(S.TABLE_NAME) AS TABLE_NAME | |
, QUOTENAME(S.TABLE_SCHEMA) AS TABLE_SCHEMA | |
, STUFF | |
( | |
( | |
SELECT ',' + COLUMN_NAME | |
FROM SRC AS SI | |
WHERE | |
SI.TABLE_NAME = S.TABLE_NAME | |
AND SI.TABLE_SCHEMA = S.TABLE_SCHEMA | |
FOR XML PATH('')),1,1,'' | |
) AS column_list | |
FROM | |
SRC AS S | |
) | |
SELECT | |
'INSERT INTO ' | |
+ S2.TABLE_NAME | |
+ '.' | |
+ S2.TABLE_SCHEMA | |
+ CHAR(13) | |
+ '(' | |
+ S2.column_list | |
+ ')' | |
+ CHAR(13) | |
+ 'SELECT ' | |
+ S2.column_list | |
+ CHAR(13) | |
+ 'FROM ' | |
+ S2.TABLE_NAME | |
+ '.' | |
+ S2.TABLE_SCHEMA | |
FROM | |
S2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment