Tuesday, October 03, 2006

Generate Insert Statement in SQL server

--Run below procedure first,
--Too execute the procedure ,
--exec generateInsertSt_sp 'authors'
--This will generate a select statement, Copy that result set run again.


create proc dbo.sp_generateInsertSt
(
@tableName sysname,
@newtableName sysname=NULL

)

as
begin


declare @column varchar(200)
DECLARE @sql varchar(5000)


if @newtableName is null
set @newtableName=@tableName

set @sql='select ''insert into '+@newtableName+'( '

select @sql=coalesce(@sql+COLUMN_NAME+',','')
from INFORMATION_SCHEMA.COLUMNS
where DATA_TYPE not in ( 'timestamp','image','sql_variant')
and TABLE_NAME=@tableName

set @sql=left(@sql,len(@sql)-1)+') select ''+'

select @sql=coalesce(@sql+
case
when DATA_TYPE='uniqueidentifier' THEN '''''''''+cast('+COLUMN_NAME+' as nvarchar(75))+'''''','','
when DATA_TYPE='varchar' THEN '''''''''+'+COLUMN_NAME+ '+'''''','','
when DATA_TYPE='char' THEN '''''''''+'+COLUMN_NAME+ '+'''''','','
when DATA_TYPE='nvarchar' THEN '''''''''+'+COLUMN_NAME+ '+'''''','','
when DATA_TYPE='nchar' THEN '''''''''+'+COLUMN_NAME+ '+'''''','','
when DATA_TYPE='text' THEN '''''''''+'+COLUMN_NAME+ '+'''''','','
when DATA_TYPE='ntext' THEN '''''''''+'+COLUMN_NAME+ '+'''''','','
when DATA_TYPE='datetime' THEN '''''''''+convert(varchar,'+COLUMN_NAME+ ',121)+'''''','','
when DATA_TYPE='smalldatetime' THEN '''''''''+convert(varchar,'+COLUMN_NAME+ ',121)+'''''','','
else '''''+cast('+COLUMN_NAME+' as nvarchar)+'','','
end,''
)
from INFORMATION_SCHEMA.COLUMNS
where DATA_TYPE not in ( 'timestamp','image','sql_variant')
and TABLE_NAME=@tableName

SET @sql=left(@sql,len(@sql)-3)
set @sql=@sql+''' from '+@tableName
print (@sql)
--exec (@sql)
end

 
Google
 
Web mallier.blogspot.com