首页 > 开发 > 综合 > 正文

将表里的数据批量生成INSERT语句的存储过程

2024-07-21 02:47:43
字体:
来源:转载
供稿:网友
将表里的数据批量生成INSERT语句的存储过程

有时候,我们需要将某个表里的数据全部导出来,迁移到另一个相同结构的库中,这里可以采取一个简便的方法,通过一个存储过程批量导出数据并生成SQL语句,非常方便。存储过程如下:

CREATE   PRoc [dbo].[spGenInsertSQL] (@tablename varchar(256))asbegindeclare @sql varchar(max)declare @sqlValues varchar(max)set @sql =' ('set @sqlValues = 'values (''+'select @sqlValues = @sqlValues + cols + ' + '','' + ' ,@sql = @sql + '[' + name + '],'from      (select case                when xtype in (48,52,56,59,60,62,104,106,108,122,127)      then 'case when '+ name +' is null then ''NULL'' else ' + 'cast('+ name + ' as varchar)'+' end'when xtype in (58,61)then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'cast('+ name +' as varchar)'+ '+'''''''''+' end'when xtype in (167)then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'when xtype in (231)then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'when xtype in (175)then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as Char(' + cast(length as varchar) + '))+'''''''''+' end'when xtype in (239)then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as Char(' + cast(length as varchar) + '))+'''''''''+' end'else '''NULL'''end as Cols,namefrom syscolumnswhere id = object_id(@tablename)) Tset @sql ='select ''INSERT INTO ['+ @tablename + ']' + left(@sql,len(@sql)-1)+') ' + left(@sqlValues,len(@sqlValues)-4) + ')'' from '+@tablenameprint @sqlexec (@sql)endGO


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表