欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

sqlserver 导出插入脚本代码

程序员文章站 2023-12-04 12:33:04
当然有其它工具可以做这件事,但如果客户不允许你在服务器乱装东西时这个脚本就会有用了。 复制代码 代码如下: declare @tbimporttables table(ta...
当然有其它工具可以做这件事,但如果客户不允许你在服务器乱装东西时这个脚本就会有用了。
复制代码 代码如下:

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