5,667,575 members and growing! (15,608 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, SQL Server, DBA, Dev

Posted: 6 Dec 2003
Updated: 16 Jan 2005
Views: 141,739
Bookmarked: 31 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
34 votes for this Article.
Popularity: 6.75 Rating: 4.41 out of 5
0 votes, 0.0%
1
1 vote, 3.0%
2
2 votes, 6.1%
3
5 votes, 15.2%
4
25 votes, 75.8%
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 .


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
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 34 (Total in Forum: 34) (Refresh)FirstPrevNext
GeneralThanks !!! Herewith Addition for inserting without taking the Primary Keys ( i.e. not having to run set identity_insert on ; .... [modified]memberyordan_georgiev1:20 19 Nov '08  
Generalthanks a lot!memberMember 238686111:16 8 Oct '08  
GeneralSimpler way, which i preferredmemberdRn-15:34 8 May '08  
GeneralGenerated script will break on Varchar fields with ( ' )memberHanysm5:36 5 Mar '08  
GeneralAuto-Increment PK ColumnsmemberJacques Doubell23:10 20 Nov '07  
GeneralTime savermemberpornoisfoei22:44 26 Jun '07  
GeneralVery useful, saved a lot of timememberOmar Al Zabir23:34 1 Apr '07  
GeneralSQL Scriptermembertommyonline5:32 28 Jan '06  
GeneralRe: SQL Scriptermemberr_maiya7:21 27 Mar '07  
GeneralEscape the quotesmemberAmit Gee9:13 18 Jan '06  
GeneralCOLLATEmembermilovanderlinden3:19 18 Jan '06  
GeneralNull Values For DateTime Data TypememberYinkaAlalade0:03 4 Nov '05  
GeneralError with type imagemembersebastien97111:01 29 Oct '05  
Generalran into a cool tool which generates SQL Insert statementsmemberPadigela11:01 14 May '05  
Generalpresuming the data type is int,bit,numeric,decimalmemberjaem0073:35 13 May '05  
GeneralRe: presuming the data type is int,bit,numeric,decimalmemberJaem00712:24 13 May '05  
GeneralHandle column names that happen to be a SQL reserved wordmemberSOG13:45 11 May '05  
GeneralThanksmembersousa19818:20 10 May '05  
GeneralDoesn't generate full INSERT statement?memberSrinivasan V4:10 7 Feb '05  
GeneralRe: Doesn't generate full INSERT statement?memberkellyxwheeler6:46 16 Feb '05  
GeneralHandling apostrophesmemberClaum8:35 28 Jan '05  
GeneralRe: Handling apostrophesmembermahpet3:32 23 Feb '05  
General