By JosephStyons

2009-06-11 17:42:28 8 Comments

We are writing a new application, and while testing, we will need a bunch of dummy data. I've added that data by using MS Access to dump excel files into the relevant tables.

Every so often, we want to "refresh" the relevant tables, which means dropping them all, re-creating them, and running a saved MS Access append query.

The first part (dropping & re-creating) is an easy sql script, but the last part makes me cringe. I want a single setup script that has a bunch of INSERTs to regenerate the dummy data.

I have the data in the tables now. What is the best way to automatically generate a big list of INSERT statements from that dataset?

The only way I can think of doing it is to save the table to an excel sheet and then write an excel formula to create an INSERT for every row, which is surely not the best way.

I'm using the 2008 Management Studio to connect to a SQL Server 2005 database.


@Thabo 2019-05-23 17:51:28

If you'd rather use Google Sheets, use SeekWell to Send the table to a Sheet, then insert rows on a schedule, as they're added to the Sheet.

See here for the step by step process , or watch a video demo of the feature here.

@Shane Fulmer 2009-06-11 17:46:27

We use this stored procedure - it allows you to target specific tables, and use where clauses. You can find the text here.

For example, it lets you do this:

EXEC sp_generate_inserts 'titles'

@JosephStyons 2009-06-11 19:57:36

This worked perfectly for me, except that the generated INSERTs don't have a semicolon @ the end. I added that and used it with success. Thanks for answering the qstn!

@jcollum 2009-07-28 19:55:19

must be something missing here, that sp doesn't seem to exist in my version of 2008

@Shane Fulmer 2009-07-28 20:32:54

@jcollum - it's actually not a built-in stored procedure. If you follow the link, you can get the text for the stored proc.

@Nimrod Shory 2009-12-07 16:11:48

I'm Getting - Msg 536, Level 16, State 5, Procedure sp_generate_inserts, Line 331 Invalid length parameter passed to the SUBSTRING function. Msg 536, Level 16, State 5, Procedure sp_generate_inserts, Line 332 Invalid length parameter passed to the SUBSTRING function. Msg 50000, Level 16, State 1, Procedure sp_generate_inserts, Line 336 No columns to select. There should at least be one column to generate the output Why?

@Gabe 2010-07-02 06:00:51

@nimrod: I'm getting the same error. Using Sql Server 2008 and schemas.

@Nimrod Shory 2010-07-04 11:36:05

@Gabriel: Sorry - i didn't get passed this - We are creating the inserts using a C# util.

@contactmatt 2011-05-11 15:47:21

All this work for something that should have been built in....

@Dan Nolan 2012-02-16 09:46:20

I got this error too. To fix it, replace "EXEC master.dbo.sp_MS_upd_sysobj_category 2" with "EXEC sp_MS_marksystemobject sp_generate_inserts" and remove the line "EXEC master.dbo.sp_MS_upd_sysobj_category 1".

@InfinitiesLoop 2012-03-21 20:32:54

SEE THE ANSWER with the most upvotes, which should be the accepted answer here. This is built-in, you don't need a stored procedure...

@CaffGeek 2013-06-25 17:37:51

@InfinitiesLoop, only that sometimes you need to be able to automate it through code, not have a user manualy perform the task through the GUI.

@Jan Święcki 2013-07-27 21:17:48

@DanielNolan could you explain your fix?

@jpgrassi 2016-06-03 02:38:43

@DanielNolan your fix solved the problem, thank you!

@David Barrows 2016-09-13 11:51:30

Note I was getting an error with that earlier version of the script, but there is a newer version (apparently for SQL 2005 and later) here: (that version did not error out for me, in SQL 2016)

@TheSoftwareJedi 2018-08-02 14:00:37

Could someone grab the proc and paste it in the answer? Firewalled here at work, and in the future that link may not work anyhow.

@Jay Cummins 2019-03-16 14:56:22

@TheSoftwareJedi: I have a copy in my snippet repo:…

@noonand 2010-12-02 13:53:51

As mentioned by @Mike Ritacco but updated for SSMS 2008 R2

  1. Right click on the database name
  2. Choose Tasks > Generate scripts
  3. Depending on your settings the intro page may show or not
  4. Choose 'Select specific database objects',
  5. Expand the tree view and check the relevant tables
  6. Click Next
  7. Click Advanced
  8. Under General section, choose the appropriate option for 'Types of data to script'
  9. Complete the wizard

You will then get all of the INSERT statements for the data straight out of SSMS.

EDIT 2016-10-25 SQL Server 2016/SSMS 13.0.15900.1

  1. Right click on the database name

  2. Choose Tasks > Generate scripts

  3. Depending on your settings the intro page may show or not

  4. Choose 'Select specific database objects',

  5. Expand the tree view and check the relevant tables

  6. Click Next

  7. Click Advanced

  8. Under General section, choose the appropriate option for 'Types of data to script'

  9. Click OK

  10. Pick whether you want the output to go to a new query, the clipboard or a file

  11. Click Next twice

  12. Your script is prepared in accordance with the settings you picked above

  13. Click Finish

@Andy 2011-10-07 11:39:08

hmm I don't know if we're using different versions of SSMS 2008 R2 but there's no 'advanced' option for me at all. what I had to do was select 'script data' in the 'choose script options' step. (BTW that option is not there in express edition)

@Klik 2016-09-08 06:47:37

GenerateData is an amazing tool for this. It's also very easy to make tweaks to it because the source code is available to you. A few nice features:

  • Name generator for peoples names and places
  • Ability to save Generation profile (after it is downloaded and set up locally)
  • Ability to customize and manipulate the generation through scripts
  • Many different outputs (CSV, Javascript, JSON, etc.) for the data (in case you need to test the set in different environments and want to skip the database access)
  • Free. But consider donating if you find the software useful :).


@transformer 2017-02-22 05:19:15

very buggy tools, the T SQL syntax is often wrong

@Klik 2017-02-22 17:06:49

I've never had any problems with it and I've used it numerous times. Perhaps you're not using the same version that the app is made for. In a worst case scenario you can create custom output by using their "Use custom HTML format". I think it's an excellent tool.

@transformer 2017-02-22 17:24:16

It does not map the types correctly, and also the sample data and insert statement create wrong quotations, I had to wade through to clean quite a bit of the script. But in the end realized dbschema was better IMHO

@Klik 2017-02-22 17:57:58

Interesting, I didn't find that and that wonder about how you were using it. Anyway, to each his own.

@transformer 2017-02-23 02:46:50

yeah it works for the very basic stuff, I let the site owner know last yr, but the output I'm referring to is the DB option to create the script for Sql Server. Its unfortunate since the script does go a long way... but on a 1000 table records insertion can be annoying.. still a nice tool for quick stuff

@Martin 2016-04-05 12:41:23

This can be done using Visual Studio too (at least in version 2013 onwards).

In VS 2013 it is also possible to filter the list of rows the inserts statement are based on, this is something not possible in SSMS as for as I know.

Perform the following steps:

  • Open the "SQL Server Object Explorer" window (menu: /View/SQL Server Object Explorer)
  • Open / expand the database and its tables
  • Right click on the table and choose "View data" from context menu
  • This will display the data in the main area
  • Optional step: Click on the filter icon "Sort and filter data set" (the fourth icon from the left on the row above the result) and apply some filter to one or more columns
  • Click on the "Script" or "Script to File" icons (the icons on the right of the top row, they look like little sheets of paper)

This will create the (conditional) insert statements for the selected table to the active window or file.

The "Filter" and "Script" buttons Visual Studio 2013:

enter image description here

@Michael12345 2016-09-05 04:36:09

This is now my preferred way of pulling records out of one database to insert somewhere else - it just seems a lot simpler than going through the wizard in SSMS.

@Mafu Josh 2016-09-13 16:05:56

I couldn't get this to export binary fields :(

@stom 2016-11-22 07:34:24

Your post is correct and easiest way using SQL Server Data Tools in Visual Studio , here is similar post which explains how generate insert statement for first 1000 rows hope helps.

@Mike Ritacco 2009-08-22 16:11:27

Microsoft should advertise this functionality of SSMS 2008. The feature you are looking for is built into the Generate Script utility, but the functionality is turned off by default and must be enabled when scripting a table.

This is a quick run through to generate the INSERT statements for all of the data in your table, using no scripts or add-ins to SQL Management Studio 2008:

  1. Right-click on the database and go to Tasks > Generate Scripts.
  2. Select the tables (or objects) that you want to generate the script against.
  3. Go to Set scripting options tab and click on the Advanced button.
  4. In the General category, go to Type of data to script
  5. There are 3 options: Schema Only, Data Only, and Schema and Data. Select the appropriate option and click on OK.

You will then get the CREATE TABLE statement and all of the INSERT statements for the data straight out of SSMS.

@Richard West 2011-05-21 21:09:45

Be sure to read Noonand's comment below -- the check box is not under SCRIPT DATA = TRUE, instead it is under General section, choose the appropriate option for 'Types of data to script'.

@tony 2013-06-22 10:24:37

If you only want to generate one insert statement do something like this; select * into newtable from existingtable where [your where clause], then just do as above on the new table

@Joe Phillips 2015-08-17 19:30:44

The Advanced button is in a really dumb spot. It's no wonder nobody ever finds this on their own. It seems like it goes with the "Save to file" option. Also, I wonder why it doesn't generate a more efficient insert statement instead of many multiple insert statements

@Alan Fluka 2015-09-07 10:10:49

This works the same way in newer versions as well. Confirmed it in SSMS 2014.

@Endy Tjahjono 2017-09-06 10:50:44

FYI if you select Data only and encounter Cyclic dependencies found error, switch to Schema and data to avoid the error. Happens in Management Studio v17.

@Gerard 2017-10-31 16:08:51

Doesn't work for a view when you e.g. want to filter the data with a where clause.

@mickeyf 2018-01-25 16:19:05

In theory creating a script for the entire DB should allow you to regenerate that DB, data and all. I do this with Postgres regularly. I tried this with SSMS 2014 and it failed when I ran the script. It did not matter whether the previous copy of the DB had been deleted first or not. It ended up inserting 100's of tables and SPs into master, which I then had to clean up. It may work fine with individual tables or with tables only, but I would recommend exercising this thoroughly before relying on it in any way.

@Michael Freidgeim 2018-02-16 11:17:15

In SSMS 17.3 you can change "Type of data to script" only if you select 1 table. For more than 1 table "Schema Only" is pre-selected and I couldn't change it.

@dkolln 2018-09-07 14:07:49

Oh my gosh that saved us $200 in licensing fees strictly just for exporting insert statements Nice!!!

@AGH 2019-03-18 09:58:42

Its not working for huge data.

@b15 2019-03-25 17:24:00

I'm getting just getting USE [DB] GO

@drumsta 2015-12-06 03:54:29

If you need a programmatic access, then you can use an open source stored procedure `GenerateInsert.

INSERT statement(s) generator

Just as a simple and quick example, to generate INSERT statements for a table AdventureWorks.Person.AddressType execute following statements:

USE [AdventureWorks];
EXECUTE dbo.GenerateInsert @ObjectName = N'Person.AddressType';

This will generate the following script:

INSERT INTO Person.AddressType
 (1,N'Billing','B84F78B1-4EFE-4A0E-8CB7-70E9F112F886',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(2,N'Home','41BC2FF6-F0FC-475F-8EB9-CEC0805AA0F2',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(3,N'Main Office','8EEEC28C-07A2-4FB9-AD0A-42D4A0BBC575',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(4,N'Primary','24CB3088-4345-47C4-86C5-17B535133D1E',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(5,N'Shipping','B29DA3F8-19A3-47DA-9DAA-15C84F4A83A5',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(6,N'Archive','A67F238A-5BA2-444B-966C-0467ED9C427F',CONVERT(datetime,'2002-06-01 00:00:00.000',121))

@anar khalilov 2017-03-22 06:00:04

nice job! simple and does what it was meant to do. hope to use this for a loong time :)

@anar khalilov 2017-03-27 10:52:07

after noticing a bug in the code, I made a pull request at github. thanks for sharing.

@user11156893 2019-04-05 04:16:36

this actually works better than EXEC sp_generate_inserts 'titles'

@user11156893 2019-04-15 22:54:06

@drumsta can you add an Include Column, Exclude Column List Parameter if needed, right now I only need few columns from my table? Thanks

@chuck 2015-04-21 23:42:26

My contribution to the problem, a Powershell INSERT script generator that lets you script multiple tables without having to use the cumbersome SSMS GUI. Great for rapidly persisting "seed" data into source control.

  1. Save the below script as "filename.ps1".
  2. Make your own modifications to the areas under "CUSTOMIZE ME".
  3. You can add the list of tables to script in any order.
  4. You can open the script in Powershell ISE and hit the Play button, or simply execute the script in the Powershell command prompt.

By default, the INSERT script generated will be "SeedData.sql" under the same folder as the script.

You will need the SQL Server Management Objects assemblies installed, which should be there if you have SSMS installed.

Add-Type -AssemblyName ("Microsoft.SqlServer.Smo, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
Add-Type -AssemblyName ("Microsoft.SqlServer.ConnectionInfo, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91")

$outputFile = ".\SeedData.sql"
$connectionString = "Data Source=.;Initial Catalog=mydb;Integrated Security=True;"

$sqlConnection = new-object System.Data.SqlClient.SqlConnection($connectionString)
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection($sqlConnection)
$srv = new-object Microsoft.SqlServer.Management.Smo.Server($conn)
$db = $srv.Databases[$srv.ConnectionContext.DatabaseName]
$scr = New-Object Microsoft.SqlServer.Management.Smo.Scripter $srv
$scr.Options.FileName = $outputFile
$scr.Options.AppendToFile = $false
$scr.Options.ScriptSchema = $false
$scr.Options.ScriptData = $true
$scr.Options.NoCommandTerminator = $true

$tables = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection




@Yordan Georgiev 2010-03-22 07:04:13

I used this script which I have put on my blog (How-to generate Insert statement procedures on sql server).

So far has worked for me, although they might be bugs I have not discovered yet .

@Jane 2010-02-07 09:35:50

Just for reference, these have moved now: stored procedure:… documentation as a series of blog posts:

@jruizaranguren 2014-09-17 10:15:43

One important advantage of this approach is the ability to add filters to the data to select.

@Erikest 2012-04-05 08:01:03

I'm using SSMS 2008 version 10.0.5500.0. In this version as part of the Generate Scripts wizard, instead of an Advanced button, there is the screen below. In this case, I wanted just the data inserted and no create statements, so I had to change the two circled propertiesScript Options

@johnnycrash 2009-06-11 19:08:23

The first link to sp_generate_inserts is pretty cool, here is a really simple version:

DECLARE @Fields VARCHAR(max); SET @Fields = '[QueueName], [iSort]' -- your fields, keep []
DECLARE @Table  VARCHAR(max); SET @Table  = 'Queues'               -- your table

SELECT @S = ISNULL(@S + '' UNION '', ''INSERT INTO ' + @Table + '(' + @Fields + ')'') + CHAR(13) + CHAR(10) + 
 ''SELECT '' + ' + REPLACE(REPLACE(REPLACE(@Fields, ',', ' + '', '' + '), '[', ''''''''' + CAST('),']',' AS VARCHAR(max)) + ''''''''') +' FROM ' + @Table + '


On my system, I get this result:

INSERT INTO Queues([QueueName], [iSort])
SELECT 'WD: Auto Capture', '10' UNION 
SELECT 'Car/Lar', '11' UNION 
SELECT 'Scan Line', '21' UNION 
SELECT 'Dynamic Template', '23' UNION 
SELECT 'Fix MICR (Supervisor)', '42' UNION 
SELECT 'Foreign MICR', '43' UNION 

@Paul Harrington 2009-07-22 17:31:17

I use sqlite to do this. I find it very, very useful for creating scratch/test databases.

sqlite3 foo.sqlite .dump > foo_as_a_bunch_of_inserts.sql

@Vineet Neema 2009-07-16 02:39:40

I have also researched lot on this, but I could not get the concrete solution for this. Currently the approach I follow is copy the contents in excel from SQL Server Managment studio and then import the data into Oracle-TOAD and then generate the insert statements

@drumsta 2016-07-29 21:16:23

Hi Vineet, if you would try my solution and let me know what doesn't suit your needs I would happy to help you with automated SQL script generation.

@BinaryHacker 2009-07-12 19:48:19

You can use SSMS Tools Pack (available for SQL Server 2005 and 2008). It comes with a feature for generating insert statements.

@Matej 2012-08-27 22:05:28

The only tool worked for very large nvarchar(max) content with tabs and new lines.

@janem 2009-07-12 02:59:59

Perhaps you can try the SQL Server Publishing Wizard

It has a wizard that helps you script insert statements.

@Brabbeldas 2013-06-27 12:36:19

it is pre-installed: “C:\Program Files (x86)\Microsoft SQL Server\90\Tools\Publishing\1.4\SqlPubWiz.exe”

@Nick DeVore 2009-06-11 18:11:12

Do you have data in a production database yet? If so, you could setup a period refresh of the data via DTS. We do ours weekly on the weekends and it is very nice to have clean, real data every week for our testing.

If you don't have production yet, then you should create a database that is they want you want it (fresh). Then, duplicate that database and use that newly created database as your test environment. When you want the clean version, simply duplicate your clean one again and Bob's your uncle.

@shahkalpesh 2009-06-11 17:52:00

Not sure, if I understand your question correctly.

If you have data in MS-Access, which you want to move it to SQL Server - you could use DTS.
And, I guess you could use SQL profiler to see all the INSERT statements going by, I suppose.

@ShuggyCoUk 2009-06-11 17:48:45

Don't use inserts, use BCP

@Steve Homer 2010-10-27 13:09:09

Valid in most cases but there can be good reasons for wanting to use inserts.

@Chris Simmons 2011-12-20 20:01:50

Indeed, @Steve Homer. Grabbing a good DB initialization script, e.g. for EF Code First projects. Yep, there are many times when I've needed this functionality. BCP just didn't fit.

@KM. 2009-06-11 17:44:14

why not just backup the data before your work with it, then restore when you want it to be refreshed?

if you must generate inserts try:

@JosephStyons 2009-06-11 17:46:22

I'd like the flexibility to edit the data in the INSERTs if I want to. Other than that, no real reason... I need to research the syntax of RESTORE and BACKUP so I can do that from a script.

Related Questions

Sponsored Content

27 Answered Questions

24 Answered Questions

[SOLVED] Check if table exists in SQL Server

24 Answered Questions

[SOLVED] Find all tables containing column with specified name - MS SQL Server

17 Answered Questions

[SOLVED] What is the best way to paginate results in SQL Server

13 Answered Questions

[SOLVED] Best way to get identity of inserted row?

  • 2008-09-03 21:32:02
  • Oded
  • 752343 View
  • 1002 Score
  • 13 Answer
  • Tags:   sql sql-server tsql

20 Answered Questions

10 Answered Questions

[SOLVED] Update a table using JOIN in SQL Server?

7 Answered Questions

4 Answered Questions

37 Answered Questions

Sponsored Content