加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQL Server 导出插入脚本代码

发布时间:2020-12-12 07:39:30 所属栏目:MsSql教程 来源:网络整理
导读:感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧! 当然有其它工具可以做这件事,但如果客户不允许你在服务器乱装东西时这个脚本就会有用了。 代码如下: DECLARE @tbImportTables table(tablename varchar(128),deleted tinyint) -- appe

感兴趣的小伙伴,下面一起跟随编程之家 52php.cn的小编两巴掌来看看吧!

当然有其它工具可以做这件事,但如果客户不允许你在服务器乱装东西时这个脚本就会有用了。

代码如下:

 
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,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,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 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读