SQL Server 导出插入脚本代码
2022-11-12 09:48:55
内容摘要
这篇文章主要为大家详细介绍了SQL Server 导出插入脚本代码,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!当然有其它工具可以做这件事,但
文章正文
这篇文章主要为大家详细介绍了SQL Server 导出插入脚本代码,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!
当然有其它工具可以做这件事,但如果客户不允许你在服务器乱装东西时这个脚本就会有用了。代码如下:
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <code> DECLARE @tbImportTables table(tablename varchar(128), deleted tinyint) -- append tables which you want to import Insert Into @tbImportTables(tablename, deleted) values( 'tentitytype' , 1) Insert Into @tbImportTables(tablename, deleted) values( 'tattribute' , 1) -- append all tables --Insert Into @tbImportTables(tablename, deleted) select table_name, 1 from INFORMATION_SCHEMA.tables where table_type = 'BASE TABLE' DECLARE @tbImportScripts table(script varchar(max)) Declare @tablename varchar(128), @deleted tinyint, @columnname varchar(128), @fieldscript varchar(max), @valuescript varchar(max), @insertscript varchar(max) Declare curImportTables Cursor For Select tablename, deleted From @tbImportTables Open curImportTables Fetch Next From curImportTables Into @tablename, @deleted WHILE @@Fetch_STATUS = 0 Begin If (@deleted = 1) begin Insert into @tbImportScripts(script) values ( 'Truncate table ' + @tablename) end Insert into @tbImportScripts(script) values ( 'SET IDENTITY_INSERT ' + @tablename + ' ON' ) set @fieldscript = '' select @fieldscript = @fieldscript + column_name + ',' from INFORMATION_SCHEMA.columns where table_name = @tablename and data_type not in( 'timestamp' , 'image' ) set @fieldscript = substring(@fieldscript, 0, len(@fieldscript)) set @valuescript = '' select @valuescript = @valuescript + 'case when ' + column_name + ' is null then ' 'null' ' else ' '' '' '' ' + convert(varchar(max), ' + column_name + ') + ' '' '' '' ' end +' ',' '+' from INFORMATION_SCHEMA.columns where table_name = @tablename and data_type not in( 'timestamp' , 'image' ) set @valuescript = substring(@valuescript, 0, len(@valuescript) - 4) set @insertscript = 'select ' 'insert into ' + @tablename + '(' + @fieldscript + ') values(' + '' '+' + @valuescript + ' + ' ')' ' from ' + @tablename Insert into @tbImportScripts(script) exec ( @insertscript) Insert into @tbImportScripts(script) values ( 'SET IDENTITY_INSERT ' + @tablename + ' OFF' ) Insert into @tbImportScripts(script) values ( 'GO ' ) Fetch Next From curImportTables Into @tablename, @deleted End Close curImportTables Deallocate curImportTables Select * from @tbImportScripts </code> |
注:关于SQL Server 导出插入脚本代码的内容就先介绍到这里,更多相关文章的可以留意
代码注释