/*
功能:对单表数据生成insert语句
约束:1. 只能单表
2. insert语句包括主键数据
3. 不进行数据有效性检查
4. 采用了简单数据处理,如果对表中含了不可转换成varchar的列,则有可能失败
5. 行中有null值的行将失败
6. 执行生成的insert语句组前,如果表有自编号字段,请先使用set identity_insert 表名 on,允许insert自动编号数据
作者: Gavin Liu
*/
declare @tableName varchar(50)
select @tableName='表名' --要生成insert数据的表名,去掉表所有者前缀(如dbo.)
declare @sqlstr varchar(max)
select @sqlstr=''
declare @fldList varchar(max),@flsValueList varchar(max)
select @fldList='',@flsValueList=''
select
@fldList = @fldList + case when len(@fldList)>0 then ',' else '' end + cols.[name],
@flsValueList = @flsValueList + case when len(@flsValueList)>0 then ',' else '' end + '''''''+cast(' + cols.[name] + ' as varchar(max))+'''''''
from
(select * from sysobjects where xtype='u') tbls
inner join syscolumns cols on cols.id=tbls.id
where tbls.[name] in (@tableName)
select @sqlstr='select ''insert into ' + @tableName + '(' + @fldList + ') values (' + @flsValueList + ')'' from ' + @tableName
execute(@sqlstr)