Click here to Skip to main content
15,879,239 members
Articles / Database Development / SQL Server
Article

Generating INSERT statements in SQL Server

Rate me:
Please Sign up or sign in to vote.
4.91/5 (89 votes)
16 Jan 2005CPOL2 min read 550.9K   12K   100   94
Stored procedure to generate INSERT..VALUES statements in SQL Server.

Image 1

Introduction

The stored procedure InsertGenerator generates the INSERT..VALUES statements for the specified table name.

Background

SQL Server doesn’t allow generation of INSERT statements for the table data, when Generate SQL Script option is selected. The workaround is to make use of DTS for transferring data across servers. However, there exists a need to generate INSERT statements from the tables for porting data. Simplest example is when small or large amount of data needs to be taken out on a removable storage media and copied to a remote location, INSERT..VALUES statements come handy.

Using the code

This small yet useful stored procedure will take as parameter the table name and generates the INSERT SQL statements for the same. The output can be redirected to either text format (Ctrl+T in Query Analyzer) or Output to a text file. The procedure accepts an input varchar type parameter that has to be the table name under consideration for statement generation.

SQL
CREATE PROC InsertGenerator
(@tableName varchar(100)) as

Then it includes a cursor to fetch column specific information (column name and the data type thereof) from information_schema.columns pseudo entity and loop through for building the INSERT and VALUES clauses of an INSERT DML statement.

SQL
--Declare a cursor to retrieve column specific information 
--for the specified table
DECLARE cursCol CURSOR FAST_FORWARD FOR 
SELECT column_name,data_type FROM information_schema.columns 
    WHERE table_name = @tableName
OPEN cursCol
DECLARE @string nvarchar(3000) --for storing the first half 
                               --of INSERT statement
DECLARE @stringData nvarchar(3000) --for storing the data 
                                   --(VALUES) related statement
DECLARE @dataType nvarchar(1000) --data types returned 
                                 --for respective columns
SET @string='INSERT '+@tableName+'('
SET @stringData=''

DECLARE @colName nvarchar(50)

FETCH NEXT FROM cursCol INTO @colName,@dataType

IF @@fetch_status<>0
    begin
    print 'Table '+@tableName+' not found, processing skipped.'
    close curscol
    deallocate curscol
    return
END

WHILE @@FETCH_STATUS=0
BEGIN
IF @dataType in ('varchar','char','nchar','nvarchar')
BEGIN
    SET @stringData=@stringData+'''''''''+
            isnull('+@colName+','''')+'''''',''+'
END
ELSE
if @dataType in ('text','ntext') --if the datatype 
                                 --is text or something else 
BEGIN
    SET @stringData=@stringData+'''''''''+
          isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+'
END
ELSE
IF @dataType = 'money' --because money doesn't get converted 
                       --from varchar implicitly
BEGIN
    SET @stringData=@stringData+'''convert(money,''''''+
        isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'
END
ELSE 
IF @dataType='datetime'
BEGIN
    SET @stringData=@stringData+'''convert(datetime,''''''+
        isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+'
END
ELSE 
IF @dataType='image' 
BEGIN
    SET @stringData=@stringData+'''''''''+
       isnull(cast(convert(varbinary,'+@colName+') 
       as varchar(6)),''0'')+'''''',''+'
END
ELSE --presuming the data type is int,bit,numeric,decimal 
BEGIN
    SET @stringData=@stringData+'''''''''+
          isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+'
END

SET @string=@string+@colName+','

FETCH NEXT FROM cursCol INTO @colName,@dataType
END

After both of the clauses are built, the VALUES clause contains a trailing comma which needs to be replaced with a single quote. The prefixed clause will only face removal of the trailing comma.

SQL
DECLARE @Query nvarchar(4000) -- provide for the whole query, 
                              -- you may increase the size

SET @query ='SELECT '''+substring(@string,0,len(@string)) + ') 
    VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' 
    FROM '+@tableName
exec sp_executesql @query --load and run the built query

Eventually, close and de-allocate the cursor created for columns information.

SQL
CLOSE cursCol
DEALLOCATE cursCol

After the procedure is compiled and created, just run it in Query Analyzer by using the following syntax:

InsertGenerator <tablename>

E.g.:

SQL
USE pubs
GO
InsertGenerator employee 
GO

Then copy the INSERT statements and run’em in the query analyzer.

Before the INSERTs are run, SET IDENTITY_INSERT <TABLENAME>ON should be passed for adding values in an identity-based column.

Points of Interest

D: T-SQL lovers might wish to extend this procedure for providing support for binary data types such as IMAGE etc.

History

  • Ver 0.1b added Dec 5, 03.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader EA
United States United States
Sumit Amar started programming in BASIC at the age of 14 in 1993, then moved on to C/UNIX.
Later in 1999, he started developing commercial applications in J2SE, J2EE and Perl. He started developing applications in .NET with ASP+ (later renamed to ASP.NET) in December 2000 with public Beta 1. He has been developing in .NET ever since.

He has an MBA degree in IT and Systems.

Sumit is a Director of Engineering at Electronic Arts, where he works on building hybrid cloud systems.

Comments and Discussions

 
QuestionThank you, Thank You :) Pin
Basil Ntinga20-Oct-11 20:33
professionalBasil Ntinga20-Oct-11 20:33 
QuestionHandling XML Datatype Pin
Badcop66619-Jun-11 12:45
Badcop66619-Jun-11 12:45 
AnswerRe: Handling XML Datatype Pin
Badcop66619-Jun-11 15:42
Badcop66619-Jun-11 15:42 
GeneralRe: Handling XML Datatype Pin
Badcop66619-Jun-11 15:45
Badcop66619-Jun-11 15:45 
GeneralMy vote of 5 Pin
Md. Abul Kasem6-Jun-11 11:42
professionalMd. Abul Kasem6-Jun-11 11:42 
GeneralMy vote of 5 Pin
Gypo2-Jun-11 4:50
Gypo2-Jun-11 4:50 
GeneralMy vote of 5 Pin
jaguarOax17-May-11 10:32
jaguarOax17-May-11 10:32 
GeneralMy vote of 5 Pin
JP®16-May-11 3:43
JP®16-May-11 3:43 
Nice Code.
GeneralMy vote of 5 Pin
George Kousis8-May-11 1:30
George Kousis8-May-11 1:30 
GeneralDoes not work with local or global temporary tables (ie #foo ##foo) Pin
Jafin30-Mar-11 17:47
Jafin30-Mar-11 17:47 
GeneralINTO Qualifier Missing Pin
RogerDodge18-Feb-11 6:41
RogerDodge18-Feb-11 6:41 
GeneralRe: INTO Qualifier Missing Pin
Sumit Amar .25-May-11 10:53
professionalSumit Amar .25-May-11 10:53 
GeneralMy vote of 5 Pin
r sukhadiya1-Feb-11 21:06
r sukhadiya1-Feb-11 21:06 
GeneralMy vote of 5 Pin
didilcool28-Jan-11 5:29
didilcool28-Jan-11 5:29 
GeneralMy vote of 5 Pin
Yatin Barmeda15-Jan-11 3:58
Yatin Barmeda15-Jan-11 3:58 
GeneralMy vote of 5 Pin
pavan1233219-Dec-10 1:53
pavan1233219-Dec-10 1:53 
GeneralGreat! Thank you! Pin
vnts722-Nov-10 23:17
vnts722-Nov-10 23:17 
GeneralMy vote of 5 Pin
Member 164164223-Sep-10 4:28
Member 164164223-Sep-10 4:28 
GeneralMy vote of 5 Pin
bytejanitor10-Aug-10 4:30
bytejanitor10-Aug-10 4:30 
QuestionReally long strings Pin
bytejanitor9-Aug-10 13:34
bytejanitor9-Aug-10 13:34 
AnswerRe: Really long strings Pin
Member 85414645-Jan-12 7:06
Member 85414645-Jan-12 7:06 
GeneralThank you for saving me time! Pin
Adrian Akison8-Jun-10 16:42
professionalAdrian Akison8-Jun-10 16:42 
GeneralTks a Lot! Pin
FernandoMartin18-Nov-09 2:10
FernandoMartin18-Nov-09 2:10 
GeneralThanks !!! Pin
aqnysos12329-Sep-09 5:11
aqnysos12329-Sep-09 5:11 
GeneralThanks a lot! Pin
Uday Takbhate7-Aug-09 2:41
Uday Takbhate7-Aug-09 2:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.