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
5 Comments:
Great it works well
5:41 AM
This comment has been removed by the author.
3:52 AM
i changed the code in a way that it returns the scripts in only one column, that way it's easier to write the script to a text file using an Ado recordset
here is my code
create proc dbo.GenerateInsertStatement
(
@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 '+isnull(cast('''''''''+COLUMN_NAME+' as nvarchar(75)),''NULL'')+'''''',''+'
when DATA_TYPE='varchar' THEN 'isnull(''''''''+'+COLUMN_NAME+ '+'''''''',''NULL'')+'','' +'
when DATA_TYPE='char' THEN 'isnull(''''''''+'+COLUMN_NAME+ '+'''''''',''NULL'')+'',''+'
when DATA_TYPE='nvarchar' THEN 'isnull(''''''''+'+COLUMN_NAME+ '+'''''''',''NULL'')+'','' +'
when DATA_TYPE='nchar' THEN 'isnull(''''''''+'+COLUMN_NAME+ '+'''''''',''NULL'')+'','' +'
when DATA_TYPE='text' THEN 'isnull(''''''''+'+COLUMN_NAME+ '+'''''''',''NULL'')+'','' +'
when DATA_TYPE='ntext' THEN 'isnull(''''''''+'+COLUMN_NAME+ '+'''''''',''NULL'')+'','' +'
when DATA_TYPE='datetime' THEN 'isnull(''''''''+convert(varchar,'+COLUMN_NAME+ ',121)+'''''''',''NULL'')+'','' +'
when DATA_TYPE='smalldatetime' THEN 'isnull(''''''''+convert(varchar,'+COLUMN_NAME+ ',121)+'''''''',''NULL'')+'','' +'
else 'isnull('''''''' + cast('+COLUMN_NAME+' as nvarchar)+ '''''''',''NULL'')+'',''+'
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
and the VB part
' script table contents
Dim objInsertScript As System.IO.StreamWriter
objInsertScript = New StreamWriter(dstScriptPath & dstInsertScriptName)
Dim oConn As New SqlClient.SqlConnection
oConn.ConnectionString = "Data Source=" & dbSourceServer & ";Integrated Security=SSPI;Initial Catalog=" & dbSourceName
Try
If oConn.State = ConnectionState.Closed Then
oConn.Open()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Dim Insert As String = ""
For Each Table In db.Tables
If Table.IsSystemObject = False And Left(Table.Name, 1) = "_" Then
'check if the table has an identity column
Dim TableHasIdentity As Boolean = False
Dim col As Column
For Each col In Table.Columns
If col.Identity = True Then
TableHasIdentity = True
End If
Next
If TableHasIdentity = True Then
Insert = Insert + "set identity_insert " & Table.Name & " on" & vbCrLf + "GO" + vbCrLf
End If
Dim oCmd As New SqlClient.SqlCommand
oCmd.Connection = oConn
oCmd.CommandTimeout = 30
oCmd.CommandType = CommandType.Text
oCmd.CommandText = " exec GenerateInsertStatement '" & Table.Name & "'"
Dim oRd As SqlClient.SqlDataReader
Try
oRd = oCmd.ExecuteReader()
While oRd.Read
Insert = Insert + oRd.GetString(0) + vbCrLf + "GO" + vbCrLf
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
If TableHasIdentity = True Then
Insert = Insert + "set identity_insert " & Table.Name & " off" & vbCrLf + "GO" + vbCrLf
End If
oRd.Close()
oCmd = Nothing
End If
Next
oConn.Close()
objInsertScript.WriteLine("-- Script to insert values in tables")
objInsertScript.WriteLine("-- AUTOMATICALLY GENERATED -- DO NOT EDIT")
objInsertScript.Write(Insert)
objInsertScript.Close()
5:06 AM
found a good version for same at
http://vyaskn.tripod.com/code.htm#inserts
It covers different scenarios in making script.
12:56 PM
I have extended same script to include '/' inside the field values. Like if you have field name as 'Total/Country' than it should allow you to generate insert statement.
View
Thanks,
Ashish
2:13 AM
Post a Comment
<< Home