16

I would like to export a ad hoc Select query result sets from SQL Server to be exported directly as Insert Statements.

I would love to see a Save As option "Insert.." along with the other current available options (csv, txt) when you right-click in SSMS. I am not exporting from an existing physical table and I have no permissions to create new tables so the options to script physical tables are not an option for me.

I have to script either from temporary tables or from the result set in the query window.

Right now I can export to csv and then import that file into another table but that's time consuming for repetitive work.

The tool has to create proper Inserts and understand the data types when it creates values for NULL values.

3
  • If you aren't exporting from an existing table, how the heck are you expecting to get a select statement turned into an insert statement?
    – Eric
    Jun 15, 2009 at 19:56
  • Yeah, are you assuming you can only insert from a table with an identical schema or something? I don't understand the difficulty.
    – dkretz
    Jun 15, 2009 at 20:43
  • 1
    When I execute a select statement, I get a result set. I want to export this result set as bunch of insert statements to recreate the same result set somewhere else. Forget about any existing tables.
    – Abdu
    Jun 15, 2009 at 22:34

9 Answers 9

15

Personally, I would just write a select against the table and generate the inserts myself. Piece of cake.

For example:

SELECT  'insert into [pubs].[dbo].[authors](
                    [au_id], 
                    [au_lname], 
                    [au_fname], 
                    [phone], 
                    [address], 
                    [city], 
                    [state], 
                    [zip], 
                    [contract])
    values( ''' + 
    [au_id] + ''', ''' + 
    [au_lname] + ''', ''' +
    [au_fname] + ''', ''' +
    [phone] + ''', ''' +
    [address] + ''', ''' +
    [city] + ''', ''' +
    [state] + ''', ''' +
    [zip] + ''', ' +
    cast([contract] as nvarchar) + ');'
FROM    [pubs].[dbo].[authors]

will produce

insert into [pubs].[dbo].[authors](
                    [au_id], 
                    [au_lname], 
                    [au_fname], 
                    [phone], 
                    [address], 
                    [city], 
                    [state], 
                    [zip], 
                    [contract])
    values( '172-32-1176', 'White', 'Johnson', '408 496-7223', '10932 Bigge Rd.', 'Menlo Park', 'CA', '94025', 1);
insert into [pubs].[dbo].[authors](
                    [au_id], 
                    [au_lname], 
                    [au_fname], 
                    [phone], 
                    [address], 
                    [city], 
                    [state], 
                    [zip], 
                    [contract])
    values( '213-46-8915', 'Green', 'Marjorie', '415 986-7020', '309 63rd St. #411', 'Oakland', 'CA', '94618', 1);
... etc ...

A couple pitfalls:

  1. Don't forget to wrap your single quotes
  2. This assumes a clean database and is not SQL Injection safe.
1
  • Thanks but that's even more cumbersome than exporting to a file and then importing, specially even more when writing complex select statements. Plus too many single quotes to worry about! :)
    – Abdu
    Jun 15, 2009 at 22:44
11

take a look at the SSMS Tools Pack add in for SSMS which allows you to do just what you need.

6
  • This creates from an existing table. I need to create from the result set in the query window.
    – Abdu
    Jun 15, 2009 at 22:40
  • it can do that too. right click on the result set and choose Script Grid Results. Jun 16, 2009 at 10:02
  • Note that @MladenPrajdic is the program author (thanks!) and that SSMS Tools Pack has become a commercial product from 2.5.0.0 released 2012-09-18. There is a 30 day demo version available, plus older versions which still are free.
    – Joel Purra
    Oct 30, 2012 at 12:38
  • 3
    not quite right. :) SSMS Tools Pack is commercial only for SSMS 2012. The users of SSMS 2008 and 2005 have the SSMS Tools Pack still for free. Oct 30, 2012 at 17:19
  • Very old post, but does this still work? Seems I can only script it to SELECT, and Im not able to save it as a file.
    – mathkid91
    May 27, 2016 at 9:23
4

ATTENTION!!! AS IS. At the start of script you can see example how to use procedure. Of course you can make INSERT expresion if you need or add DataTypes for your required conversion.

The script's result is concated SELECT expresions with UNION ALL. Be careful with collation of your data base. I didn't test other collation more than I need.

For long lenght fields I recomend use [Save Result As..] in Result grid instead Copy. Bacause you may get cutted script.

/*
USE AdventureWorks2012
GO

IF OBJECT_ID('tempdb..#PersonTbl') IS NOT NULL
    DROP TABLE #PersonTbl;
GO

SELECT TOP (100)
        BusinessEntityID
      , PersonType
      , NameStyle
      , Title
      , FirstName
      , MiddleName
      , LastName
      , Suffix
      , EmailPromotion
      , CONVERT(NVARCHAR(MAX), AdditionalContactInfo) AS [AdditionalContactInfo]
      , CONVERT(NVARCHAR(MAX), Demographics) AS [Demographics]
      , rowguid
      , ModifiedDate
INTO    #PersonTbl
FROM    Person.Person

 EXEC dbo.p_GetTableAsSqlText
    @table_name = N'#PersonTbl'

EXEC dbo.p_GetTableAsSqlText
    @table_name = N'Person'
    , @table_owner = N'Person'
*/
    /*********************************************************************************************/
IF OBJECT_ID('dbo.p_GetTableAsSqlText', 'P') IS NOT NULL
    DROP PROCEDURE dbo.p_GetTableAsSqlText
GO

CREATE PROCEDURE [dbo].[p_GetTableAsSqlText]
    @table_name NVARCHAR(384) /*= 'Person'|'#Person'*/
  , @database_name NVARCHAR(384) = NULL /*= 'AdventureWorks2012'*/
  , @table_owner NVARCHAR(384) = NULL /*= 'Person'|'dbo'*/
 /*WITH ENCRYPTION, RECOMPILE, EXECUTE AS CALLER|SELF|OWNER| 'user_name'*/
AS /*OLEKSANDR PAVLENKO p_GetTableAsSqlText ver.2016.10.11.1*/
    DECLARE @isTemporaryTable BIT = 0

/*[DATABASE NAME]*/
    IF (PATINDEX('#%', @table_name) <> 0)
        BEGIN
            SELECT  @database_name = DB_NAME(2) /*2 - 'tempdb'*/
                  , @isTemporaryTable = 1
        END
    ELSE
        SET @database_name = COALESCE(@database_name, DB_NAME())
/*END [DATABASE NAME]*/

/*[SCHEMA]*/
    SET @table_owner = COALESCE(@table_owner, SCHEMA_NAME())

    DECLARE @database_nameQuoted NVARCHAR(384) = QUOTENAME(@database_name, '')
    DECLARE @table_ownerQuoted NVARCHAR(384) = QUOTENAME(@table_owner, '')
    DECLARE @table_nameQuoted NVARCHAR(384) = QUOTENAME(@table_name, '')

    DECLARE @full_table_name NVARCHAR(769)
 /*384 + 1 + 384*/
    DECLARE @table_id INT

    SET @full_table_name = CONCAT(@database_nameQuoted, '.', @table_ownerQuoted, '.', @table_nameQuoted)
    SET @table_id = OBJECT_ID(@full_table_name)

    CREATE TABLE #ColumnTbl
        (
         ColumnId INT
       , ColName sysname COLLATE DATABASE_DEFAULT
       , TypeId TINYINT
       , TypeName sysname COLLATE DATABASE_DEFAULT
       , TypeMaxLength INT
        ) 

    DECLARE @dynSql NVARCHAR(MAX) = CONCAT('
INSERT INTO #ColumnTbl
SELECT  ISC.ORDINAL_POSITION AS [ColumnId]
      , ISC.COLUMN_NAME AS [ColName]
      , T.system_type_id AS [TypeId]
      , ISC.DATA_TYPE AS [TypeName]
      , ISC.CHARACTER_MAXIMUM_LENGTH AS [TypeMaxLength]
FROM    ', @database_name, '.INFORMATION_SCHEMA.COLUMNS AS [ISC]
        INNER JOIN ', @database_name, '.sys.objects AS [O] ON ISC.TABLE_NAME = O.name
        INNER JOIN ', @database_name, '.sys.types AS [T] ON ISC.DATA_TYPE = T.name
WHERE   ISC.TABLE_CATALOG = "', @database_name, '"
        AND ISC.TABLE_SCHEMA = "', @table_owner, '"
        AND O.object_id = ', @table_id)

    IF (@isTemporaryTable = 0)
        SET @dynSql = CONCAT(@dynSql, '
        AND ISC.TABLE_NAME = "', @table_name, '"
')
    ELSE
        SET @dynSql = CONCAT(@dynSql, '
        AND ISC.TABLE_NAME LIKE "', @table_name, '%"
')

    SET @dynSql = REPLACE(@dynSql, '"', '''')
    EXEC(@dynSql)

    DECLARE @columnNamesSeparated NVARCHAR(MAX) = SUBSTRING((SELECT ', [' + C.ColName + ']' AS [text()]
                                                             FROM   #ColumnTbl AS [C]
                                                             ORDER BY C.ColumnId
                                                            FOR
                                                             XML PATH('')
                                                            ), 2, 4000)
    --SELECT  @columnNamesSeparated

    DECLARE @columnNamesSeparatedWithTypes NVARCHAR(MAX) = SUBSTRING((SELECT    '+", " + "CONVERT(' + (CASE C.TypeId
                                                                                                         WHEN 231 /*NVARCHAR*/
                                                                                                         THEN CONCAT(C.TypeName, '(',
                                                                                                                     (CASE WHEN C.TypeMaxLength = -1 THEN 'MAX'
                                                                                                                           ELSE CONVERT(NVARCHAR(MAX), C.TypeMaxLength)
                                                                                                                      END), ')')
                                                                                                         WHEN 239 /*NCHAR*/
                                                                                                         THEN CONCAT(C.TypeName, '(', C.TypeMaxLength, ')') 
                                                                                                      /*WHEN -1 /*XML*/ THEN '(MAX)'*/
                                                                                                         ELSE C.TypeName
                                                                                                       END) + ', "+ COALESCE('
                                                                                + (CASE C.TypeId
                                                                                     WHEN 56 /*INT*/ THEN 'CONVERT(NVARCHAR(MAX), [' + C.ColName + '])'
                                                                                     WHEN 40 /*DATE*/
                                                                                     THEN 'N"""" + CONVERT(NVARCHAR(MAX), [' + C.ColName + '], 101) + """"'
                                                                                     WHEN 60 /*MONEY*/ THEN 'CONVERT(NVARCHAR(MAX), [' + C.ColName + '])'
                                                                                     WHEN 61 /*DATETIME*/
                                                                                     THEN '"""" + CONVERT(NVARCHAR(MAX), [' + C.ColName + '], 21) + """"'
                                                                                     WHEN 104 /*BIT*/ THEN 'CONVERT(NVARCHAR(MAX), [' + C.ColName + '])'
                                                                                     WHEN 106 /*DECIMAL*/ THEN 'CONVERT(NVARCHAR(MAX), [' + C.ColName + '])'
                                                                                     WHEN 127 /*BIGINT*/ THEN 'CONVERT(NVARCHAR(MAX), [' + C.ColName + '])'
                                                                                     WHEN 189 /*TIMESTAMP*/
                                                                                     THEN 'N"""" + CONVERT(NVARCHAR(MAX), SUBSTRING([' + C.ColName
                                                                                          + '], 1, 8000), 1) + """"'
                                                                                     WHEN 241 /*XML*/
                                                                                     THEN '"""" + CONVERT(NVARCHAR(MAX), [' + C.ColName + ']) + """"'
                                                                                     ELSE 'N"""" + CONVERT(NVARCHAR(MAX), REPLACE([' + C.ColName
                                                                                          + '], """", """""")) + """"'
                                                                                   END) + ' , "NULL") + ") AS [' + C.ColName + ']"' + CHAR(10) COLLATE DATABASE_DEFAULT AS [text()]
                                                                      FROM      #ColumnTbl AS [C]
                                                                      ORDER BY  C.ColumnId
                                                                     FOR
                                                                      XML PATH('')
                                                                     ), 9, 100000)

/*SELECT @columnNamesSeparated, @full_table_name*/
    DECLARE @dynSqlText NVARCHAR(MAX) = CONCAT(N'
SELECT (CASE WHEN ROW_NUMBER() OVER (ORDER BY (SELECT   1 )) = 1 THEN "
/*INSERT INTO ', @full_table_name, '
     (', @columnNamesSeparated, '
     )*/', '
SELECT T.* /*INTO #ResultTbl*/
FROM (
"
                ELSE "UNION ALL "
                END) + "SELECT "+ ', @columnNamesSeparatedWithTypes, ' FROM ', @full_table_name)
    SET @dynSqlText = CONCAT(@dynSqlText, ' UNION ALL SELECT ") AS [T]

/*SELECT *
FROM #ResultTbl*/
"')

    SET @dynSqlText = REPLACE(@dynSqlText, '"', '''')
    --SELECT  @dynSqlText AS [XML_F52E2B61-18A1-11d1-B105-00805F49916B]
    EXEC(@dynSqlText)

    IF OBJECT_ID('tempdb..#ColumnTbl') IS NOT NULL
        DROP TABLE #ColumnTbl;
GO
3

It's not exactly what the OP was asking, but if you want to generate an insert script for all records in a table, you can do it in SSMS (at least 2012 - possibly older versions) without any additional add-ons.

Right-click on the Database containing the table(s) housing your data and hit Tasks > Generate Scripts. You'll be taken to a wizard like you see below.

Just hit Next if this first screen is displayed. Just hit Next if this first screen is displayed.

Select the table(s) for which you would like to generate the script. Select the table(s) for which you would like to generate the script.

Select how you want your script outputted. Select how you want your script outputted. (I like the "new query window" option)
I like the "new query window" option.

Hit the Advanced button and select Data only for Types of data to script Hit the Advanced button and select "Data only" for "Types of data to script"
You may want to look over the options to see if there's anything else you want to modify. Hit Ok when done.

Hit Next until you get to this screen. Once everything goes green you'll have your insert script! Hit Next until you get to this screen. Once everything goes green you'll have your script!
I like to leave this screen open while I test out my script to see if I need to make any tweaks.

1
  • That gives all the data. In my case I it will result in 2 GB of data for a certain table. I want to create a smaller test set for a test database.
    – Roel
    Sep 13, 2017 at 14:56
2

I know it's not exactly what you're looking for, but you can do an insert off of a select statement:

INSERT INTO tbl(a,b) SELECT c,d FROM tbl2 WHERE c IN(...)

Obviously this is quite rough, but I hope it get's the point of what I'm trying to say across.

2
  • I want ready to execute Insert statements so I can copy them to be executed somewhere else.
    – Abdu
    Jun 15, 2009 at 22:36
  • Plus I can't create new tables if you're saying tbl is a new table. I thought my question was pretty informative.
    – Abdu
    Jun 15, 2009 at 22:49
2

Squirrel SQL can also do this.

Write an SQL query, execute it to test. Then highlight it, and select Script/Insert statement (don't remember the exact wording).

1
  • 1
    In SQuirrel SQL Client Version 3.2.1, the menu item path is "Session/Scripts/Create Data Script from SQL". I just re-discovered it thanks to this comment. Thank heavens for SO! Mar 9, 2011 at 15:03
1

TOAD can do this from the data grid Save As menu.

2
  • Can't see this in the freeware version. I see an Export Wizard and a 'SQL Script' output format and then it says this format has no license. I assume it means I need to buy the commercial version. I am not willing to pay $595 (their least expensive version) to have this feature.
    – Abdu
    Jun 16, 2009 at 0:08
  • This feature may not be available in all versions and/or platforms, I'm using 9.7 for Oracle. IMHO, TOAD is easily worth the price of admission, though obviously budgets and value scales differ. Jun 16, 2009 at 19:17
1

WinSQL at www.synametrics.com has that feature and it's pretty handy. Not sure if that feature is in the free version - but you get the Professional version to try for 30 days anyway.

It's a very handy and easy to use query tool for any ODBC connected database.

1
  • WinSQL does it. Too bad it's only in the Pro version which is $249.
    – Abdu
    Jun 15, 2009 at 23:13
0

I wrote a script for this problem that should work on any table. (I say "should" because the script isn't 100% tested and is still a little rough.) You can find it at http://www.jessemclain.com/downloads/code/sql/spd_Tool_Get_Insert_Into_Values.sql.txt

There's some junk at the bottom of the file that the hosting company appends, just strip that off. To run, just change the value of @Source_Table to your table.

NOTE: the text file I posted renders ok in Firefox 3.0.11, but not in IE7.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.