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

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 yllaji 的 blog

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

create   proc spgeninsertsql (@tablename varchar(256))

as

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 '+@tablename

--print @sql

exec (@sql)

end

go

本文关键:根据表中数据生成insert语句的存储过程
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top