How can I create INSERT scripts automatically from existing SQL Server data?

I’m working on a project where I need to generate test data for our database. Right now I have sample data stored in various tables that I imported from Excel using MS Access.

The problem is that I want to create a single script file with INSERT statements so I can easily recreate this test data whenever needed. Currently my process involves dropping tables, recreating them, and then running Access queries to import the data again.

I already have all the sample records in my database tables. Is there a good method to automatically create INSERT statements from this existing data? I thought about exporting to Excel and using formulas to build the INSERT commands, but that seems like a messy approach.

I’m working with SQL Server 2005 and using Management Studio 2008. What’s the most efficient way to generate these INSERT scripts from my current table data?

hmm interesting approaches above! have you considered using bcp utility for this? it can export data and then you could script the inserts from there. also curious - how big are these tables you’re working with? and do you need this as a one-time thing or will you be regenerating these scripts regulary?

SQL Server Management Studio has a built-in feature that handles this task efficiently. Navigate to the database in Object Explorer, right-click and select Tasks > Generate Scripts. This opens the Generate Scripts Wizard where you can specify which tables to include and crucially, set the scripting options to include data. In the Advanced Scripting Options, change the “Types of data to script” setting from “Schema only” to either “Data only” or “Schema and data” depending on your needs. The wizard will then create a comprehensive script file containing all the INSERT statements for your existing data. I’ve used this method extensively for creating deployment scripts and it handles data types, null values, and special characters properly without the manual formatting issues you’d encounter with Excel formulas.

theres also a quick way using ssms query window - just write a select statement that builds the insert commands. something like SELECT 'INSERT INTO tablename VALUES (' + field1 + ',' + field2 + ')' FROM yourtable and it generates all the insert statements automatically. works great for smaller tables