Click here to Skip to main content
11,408,708 members (59,430 online)
Click here to Skip to main content

Generating INSERT statements in SQL Server

, 16 Jan 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
Stored procedure to generate INSERT..VALUES statements in SQL Server.


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


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.

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.

--Declare a cursor to retrieve column specific information 
--for the specified table
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
    print 'Table '+@tableName+' not found, processing skipped.'
    close curscol
    deallocate curscol

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

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

FETCH NEXT FROM cursCol INTO @colName,@dataType

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.

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.

CLOSE cursCol

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

InsertGenerator <tablename>


USE pubs
InsertGenerator employee 

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.


  • Ver 0.1b added Dec 5, 03.


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


About the Author

Sumit Amar .
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.
Follow on   Twitter

Comments and Discussions

GeneralVery helpful PinmemberRUs12318-Nov-14 0:03 
QuestionYour procedure is helpful PinmemberGeorge daniel14-Jul-14 22:00 
GeneralThanks a lot PinmemberRakeshKr11-Jun-13 2:48 
QuestionGenerate insert for varbinary fields PinprofessionalDiana NoWay16-Apr-13 10:28 
QuestionThanks PinmemberEddy Nijs15-Oct-12 21:42 
Generalthnks PinmemberPayitax123316-Aug-12 16:03 
GeneralMy vote of 5 PinmemberPayitax123316-Aug-12 16:01 
QuestionAwesome! Pinmemberjaaaaaac3-Jul-12 5:50 
Questioni would say AWESOME dude PinmemberNikhil Bhivgade25-Jun-12 2:13 
NewsSQL Server Management Studio does this. PinmemberAlexandru Lungu2-May-12 2:50 
SQL Server doesn’t allow generation of INSERT statements for the table data, when Generate SQL Script option is selected.

This is an inaccurate statement... nowadays! I assume that almost 10 years ago when the article was first published, that was the case, but not anymore.

SQL Server Management Studio (even the express edition) does this. But not by default.

You're looking for this Types of data to script from the Generate and Publish Scripts wizard:

(Right click on db -> Tasks -> Generate Scripts -> Set Scripting Options -> Advanced -> Types of data to script: (Schema only (default) | Data only | Schema and data))


QuestionNULLs are not handled correctly. Causing issues with nullabel UniqueIdentifier columns. PinmemberRS Reddy220-Apr-12 13:30 
AnswerRe: NULLs are not handled correctly. Causing issues with nullabel UniqueIdentifier columns. Pinmemberbencejoful12-Jun-12 9:17 
SuggestionReady to use Stored Procedure for generating INSERT statements PinmemberMohammed_Rashid12-Mar-12 22:04 
Questionsimply awesome man PinmemberFarhan Asif12-Mar-12 5:09 
QuestionAnother tool with more features PinmemberRishikesh_716-Feb-12 4:42 
QuestionGenerate Insert script using C# : Check this out PinmemberRishikesh_716-Feb-12 4:39 
GeneralMy vote of 5 [modified] PinmemberAmol_B7-Feb-12 2:00 
GeneralMy vote of 5 Pinmemberbtrain24-Jan-12 13:51 
QuestionHow to add a WHERE param PinmemberMember 63398310-Jan-12 3:47 
AnswerRe: How to add a WHERE param PinmemberHawkeye367718-Apr-12 13:00 
GeneralExcellent! Thanks for sharing PinmemberNatreen12-Dec-11 3:57 
GeneralThanks! PinmemberMember 84519141-Dec-11 16:29 
QuestionThanks lot Pinmemberbasheer97127-Oct-11 1:44 
QuestionThank you, Thank You :) PinmemberBasil Ntinga20-Oct-11 21:33 
QuestionHandling XML Datatype PinmemberBadcop66619-Jun-11 13:45 
AnswerRe: Handling XML Datatype PinmemberBadcop66619-Jun-11 16:42 
GeneralRe: Handling XML Datatype PinmemberBadcop66619-Jun-11 16:45 
GeneralMy vote of 5 PinmemberPolash.IT6-Jun-11 12:42 
GeneralMy vote of 5 PinmemberGypo2-Jun-11 5:50 
GeneralMy vote of 5 PinmemberjaguarOax17-May-11 11:32 
GeneralMy vote of 5 PinmemberJP®16-May-11 4:43 
GeneralMy vote of 5 PinmemberGeorge Kousis8-May-11 2:30 
GeneralDoes not work with local or global temporary tables (ie #foo ##foo) PinmemberJafin30-Mar-11 18:47 
GeneralINTO Qualifier Missing PinmemberRogerDodge18-Feb-11 7:41 
GeneralRe: INTO Qualifier Missing PinmemberSumit Amar .25-May-11 11:53 
GeneralMy vote of 5 Pinmemberr sukhadiya1-Feb-11 22:06 
GeneralMy vote of 5 Pinmemberdidilcool28-Jan-11 6:29 
GeneralMy vote of 5 PinmemberYatin Barmeda15-Jan-11 4:58 
GeneralMy vote of 5 Pinmemberpavan1233219-Dec-10 2:53 
GeneralGreat! Thank you! Pinmembervnts723-Nov-10 0:17 
GeneralMy vote of 5 PinmemberMember 164164223-Sep-10 5:28 
GeneralMy vote of 5 Pinmemberbytejanitor10-Aug-10 5:30 
QuestionReally long strings Pinmemberbytejanitor9-Aug-10 14:34 
AnswerRe: Really long strings PinmemberMember 85414645-Jan-12 8:06 
GeneralThank you for saving me time! PinmemberAdrian Akison8-Jun-10 17:42 
GeneralTks a Lot! PinmemberFernandoMartin18-Nov-09 3:10 
GeneralThanks !!! Pinmemberaqnysos12329-Sep-09 6:11 
GeneralThanks a lot! PinmemberUday Takbhate7-Aug-09 3:41 
GeneralThank you! PinmemberBruceL21-May-09 6:24 
QuestionHow to emulate SQLPUBWIZ? [modified] Pinmemberapergiel11-May-09 13:10 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150414.5 | Last Updated 17 Jan 2005
Article Copyright 2003 by Sumit Amar .
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid