Skip to content

Instantly share code, notes, and snippets.

@monkeyhouse
Created October 22, 2018 14:32
Show Gist options
  • Save monkeyhouse/af4ae38409f1d03818dd03525a31fdd4 to your computer and use it in GitHub Desktop.
Save monkeyhouse/af4ae38409f1d03818dd03525a31fdd4 to your computer and use it in GitHub Desktop.
Write statements to copy table data from source db to destination db for tables with identity inserts
declare @db_to varchar(100) = '[to].[dbo].'
declare @db_from varchar(100) = '[from].[dbo].'
declare @tables varchar(1000) = 'TABLE1,TABLE2,TABLE3'
declare @copy_scripts table
(
id integer identity(1,1),
table_name varchar(200),
copy_statement varchar(4000),
id_insert_on varchar(200),
id_insert_off varchar(200)
)
--select data from dbo.Split( 'as,vc',',')
;
WITH CTE_TableName AS (
select top 10000
FieldA = object_name(object_id),
FieldB = name
from sys.all_columns
where object_id in ( select object_id(Data) from dbo.split( @tables, ',' ))
order by object_name(object_id) asc , column_id asc
),
Table_And_Cols
AS
(
SELECT
'T' = t0.FieldA
,
'C' = STUFF((
SELECT ', ' + t1.FieldB
FROM CTE_TableName t1
WHERE t1.FieldA = t0.FieldA
ORDER BY t1.FieldB
FOR XML PATH('')), 1, LEN(','), '')
FROM CTE_TableName t0
GROUP BY t0.FieldA
)
insert into @copy_scripts
(
table_name,
copy_statement,
id_insert_on,
id_insert_off
)
select
'Table' = t,
'Copy' = 'insert into ' + @db_to + t + '(' + c + ' )' + ' select ' + c + ' from ' + @db_from + t ,
'Ins_On' = 'SET IDENTITY_INSERT ' + @db_to + t + ' ON',
'Ins_Off' = 'SET IDENTITY_INSERT ' + @db_to + t + ' OFF'
from Table_And_Cols
--select * from @copy_scripts
declare @table_name varchar(200)
declare @tx_table varchar(max), @tx_on varchar(max), @tx_copy varchar(max),@tx_off varchar(max)
DECLARE column_cursor CURSOR
FOR SELECT table_name ,id_insert_on ,copy_statement ,id_insert_off FROM @copy_scripts
OPEN column_cursor
FETCH NEXT FROM column_cursor into @tx_table, @tx_on, @tx_copy, @tx_off;
print '------------- IDENTITY COPY SCRIPTS ----------------'
while @@FETCH_STATUS = 0
begin
print '/* Copy data for table ' + @tx_table + ' */ '
print @tx_on
print @tx_copy
print @tx_off
print ''
print '-----------------------------'
FETCH NEXT FROM column_cursor into @tx_table, @tx_on, @tx_copy, @tx_off;
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment