Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tool to export result set from SQL to Insert statements?

Tags:

sql

sql-server

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.

like image 774
Abdu Avatar asked Jun 15 '09 19:06

Abdu


2 Answers

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.
like image 113
John MacIntyre Avatar answered Sep 19 '22 19:09

John MacIntyre


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

like image 39
Mladen Prajdic Avatar answered Sep 19 '22 19:09

Mladen Prajdic