• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

根据表中数据生成insert语句的存储过程_sqlserver

sqlserver 搞代码 3年前 (2018-06-17) 86次浏览 已收录 0个评论

有个缺点……就是标识种子的列 也insert了

CREATE   proc spGenInsertSQL (@tablename varchar(256))

as

http://www.gaodaima.com/?p=37388根据表中数据生成insert语句的存储过程_sqlserver

begin

declare @sql varchar(8000)

declare @sqlValues varchar(8000)

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

         from syscolumns 

        where id = object_id(@tablename)

      ) T

set @sql =’select ”INSERT INTO [‘+ @tablename + ‘]’ + left(@sql,len(@sql)-1)+’) ‘ + left(@sqlValues,len(@sqlValues)-4) + ‘)” from ‘[email protected]

–print @sql

exec (@sql)

end

GO

欢迎大家阅读《根据表中数据生成insert语句的存储过程_sqlserver,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址