Click here to Skip to main content
6,629,377 members and growing! (18,819 online)
Email Password   helpLost your password?
Database » Database » SQL Server     Intermediate

Generating INSERT statements in SQL Server

By Sumit Amar .

Stored procedure to generate INSERT..VALUES statements in SQL Server.
C++, SQL, Windows, Visual Studio, SQL 2000, DBA, Dev
Posted:6 Dec 2003
Updated:16 Jan 2005
Views:174,089
Bookmarked:51 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
42 votes for this article.
Popularity: 7.25 Rating: 4.47 out of 5

1
1 vote, 2.4%
2
2 votes, 4.9%
3
6 votes, 14.6%
4
32 votes, 78.0%
5

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.

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

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.

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
DEALLOCATE cursCol

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

InsertGenerator <tablename>

E.g.:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Sumit Amar .


Member
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's continuing development in .NET (ASP.NET, C#) ever since.

He has an MBA degree in IT and Systems besides his 200+ certifications including MCSD.NET, SCJP, MCTS, MCITP (Administrator and Developer), SCWCD, OCP-DBA and numerous Brainbench certifications (Transcript ID 2232802, World rank 3).

He is a Lead Software Development Engineer at Microsoft Corporation, Redmond WA, where he works majorly on AJAX, .NET, SOAP, Web Services and Secure applications.
Occupation: Web Developer
Location: United States United States

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 44 (Total in Forum: 44) (Refresh)FirstPrevNext
GeneralTks a Lot! PinmemberFernandoMartin3:10 18 Nov '09  
GeneralThanks !!! Pinmemberaqnysos1236:11 29 Sep '09  
GeneralThanks a lot! PinmemberUday Takbhate3:41 7 Aug '09  
GeneralThank you! PinmemberBruceL6:24 21 May '09  
QuestionHow to emulate SQLPUBWIZ? [modified] Pinmemberapergiel13:10 11 May '09  
Generalfine Script, updated with schema of table Pinmemberspider_pat2:26 5 Mar '09  
GeneralPerfect!!!! PinmemberPatrick_SURFThru4:10 4 Feb '09  
GeneralMuchas Gracias PinmemberGalo Solís10:10 19 Jan '09  
GeneralThanks !!! Herewith Addition for inserting without taking the Primary Keys ( i.e. not having to run set identity_insert on ; .... [modified] Pinmemberyordan_georgiev1:20 19 Nov '08  
Generalthanks a lot! PinmemberMember 238686111:16 8 Oct '08  
GeneralSimpler way, which i preferred PinmemberdRn-15:34 8 May '08  
GeneralRe: Simpler way, which i preferred Pinmembergalsont0:58 12 Mar '09  
GeneralGenerated script will break on Varchar fields with ( ' ) PinmemberHanysm5:36 5 Mar '08  
GeneralAuto-Increment PK Columns PinmemberJacques Doubell23:10 20 Nov '07  
GeneralTime saver Pinmemberpornoisfoei22:44 26 Jun '07  
GeneralVery useful, saved a lot of time PinmemberOmar Al Zabir23:34 1 Apr '07  
GeneralSQL Scripter Pinmembertommyonline5:32 28 Jan '06  
GeneralRe: SQL Scripter Pinmemberr_maiya7:21 27 Mar '07  
GeneralEscape the quotes PinmemberAmit Gee9:13 18 Jan '06  
GeneralCOLLATE Pinmembermilovanderlinden3:19 18 Jan '06  
GeneralNull Values For DateTime Data Type PinmemberYinkaAlalade0:03 4 Nov '05  
GeneralError with type image Pinmembersebastien97111:01 29 Oct '05  
Generalran into a cool tool which generates SQL Insert statements PinmemberPadigela11:01 14 May '05  
Generalpresuming the data type is int,bit,numeric,decimal Pinmemberjaem0073:35 13 May '05  
GeneralRe: presuming the data type is int,bit,numeric,decimal PinmemberJaem00712:24 13 May '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 16 Jan 2005
Editor: Smitha Vijayan
Copyright 2003 by Sumit Amar .
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project