declare @WhereClause varchar(1024)
declare @IdentityInsert int
declare @ColName sysname
declare @ColType tinyint
declare @ColStatus tinyint
declare @DebugMode bit
declare @ColList nvarchar(4000)
declare @ValList nvarchar(4000)
declare @SQL1 nvarchar(1000)
declare @SQL2 nchar(10)
declare @SQL3 nchar(1000)
set @WhereClause = '' -- limit scope of inserts
set @DebugMode = 0 -- set to 1 if you only want a script
set @ValList = ''
set @SQL1 = 'select replace(''insert into ' + @TableName + ' ('
set @SQL2 = ') values ('
set @SQL3 = ')'', ''''''null'''''', ''null'') from ' + @TableName
select c.name, c.xtype, c.status
from syscolumns c
inner join sysobjects o
on o.id = c.id
where o.name = @TableName
and o.xtype in ('U', 'S')
order by ColID
fetch next from csrColumns into @ColName, @ColType, @ColStatus
begin
set @ColList = @ColList + ' ' + @ColName
if @ColType in (173, 104, 106, 62, 56, 60, 108, 59, 52, 122, 48, 165) -- numeric types (nulls not supported yet)
set @ValList = @ValList + ' ''+convert(varchar(200),' + @ColName + ')+'''
else if @ColType in (175, 239, 231, 231, 167) -- uid and string types
set @ValList = @ValList + ' ''''''+isnull(' + @ColName + ',''null'')+'''''''
else if @ColType in (58, 61) -- dates (nulls not supported yet)
set @ValList = @ValList + ' ''''''+convert(varchar(200),' + @ColName + ')+'''''''
else if @ColType = 36 -- uniqueidentfiers (nulls not supported yet)
set @ValList = @ValList + ' ''''{''+convert(varchar(200),' + @ColName + ')+''}'''''
if @DebugMode = 1 begin print '-- @ValList: ' + rtrim(@ValList) end
if (@ColStatus & 0x80) = 0x80 begin set @IdentityInsert = 1 end -- Check if column has Identity attribute
fetch next from csrColumns into @ColName, @ColType, @ColStatus
end
deallocate csrColumns
set @ValList = replace(ltrim(@ValList), ' ', ', ')
print 'set identity_insert ' + @TableName + ' on'
print @SQL1 + @ColList + @SQL2 + @ValList + @SQL3 + ' ' + @WhereClause
else
exec (@SQL1 + @ColList + @SQL2 + @ValList + @SQL3 + ' ' + @WhereClause)
print 'set identity_insert ' + @TableName + ' off'