Generate Insert Statements For a SQL Server Table

Microsoft SQL Server Database Publishing Wizard is a great tool to generate script for both schema and data for a database. However what if you were to write a script that could do that for you.

Here’s a real cool script written by johnnycrash that generates Insert Statements for a SQL Server Table.

For demonstration purposes, I am using the Culture table of the AdventureWorks database.

USE AdventureWorks
GO
DECLARE @Columns VARCHAR(max);
SET @Columns = '[CultureID], [Name], [ModifiedDate]'
DECLARE @Table VARCHAR(max);
SET @Table = 'Production.Culture'

DECLARE @SQL VARCHAR(max)
SET @SQL = 'DECLARE @S VARCHAR(MAX)
SELECT @S = ISNULL(@S + '' UNION '',
''INSERT INTO '
+ @Table + '(' + @Columns + ')'')
+ CHAR(13) + CHAR(10)
+ ''SELECT '' + '
+ REPLACE(REPLACE(REPLACE(@Columns, ',', ' + '', '' + '),
'[', ''''''''' + CAST('),']',' AS VARCHAR(max)) + ''''''''')
+' FROM ' + @Table
+ ' PRINT @S'

EXEC (@SQL)

OUTPUT

image

Now that’s cool!

3 comments:

  1. Check out http://www.sqlscripter.com to generate insert scripts. Very easy to use and very quick.

    ReplyDelete
  2. There is a number of scripts available to perform this data transformation task. The problem with those scripts that all of them database specific and they do not work with textiles

    Advanced ETL processor can generate Insert scripts from any data source including text files
    http://www.dbsoftlab.com/generating-insert-statements.html

    ReplyDelete
  3. Thanks. It worked for me.

    ReplyDelete