栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 系统运维 > 数据库 > MySQL > MsSql

sqlserver 导出插入脚本代码

MsSql 更新时间:发布时间: 百科书网 趣学号
当然有其它工具可以做这件事,但如果客户不允许你在服务器乱装东西时这个脚本就会有用了。
复制代码 代码如下:
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

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/170207.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号