Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I am trying to write an SQL script to create an insert statement for each row of table TEST which has field A (int) and field B varchar(30), in my MS SQL database.

I would like to save those insert statements into a txt file to be able to apply that data back to another database.

Any idea about how to do it?

share|improve this question

migrated from stackoverflow.com Jun 29 '12 at 16:23

This question came from our site for professional and enthusiast programmers.

2  
What have you tried? Where are you stuck? –  Heinzi Jun 29 '12 at 16:06
    
What you really need is to copy data from sql instances (The first two hits should work: [one](stackoverflow. –  Justin Pihony Jun 29 '12 at 16:08

4 Answers 4

  1. Right-click on your Database in Object Explorer
  2. Select Tasks -> Generate Scripts...
  3. In that wizard you will be able to select the desired object(s) that you'd like to script out
  4. The next portion has an Advanced button, click that
  5. Under General, you will see the option called Types of data to script. The options are Schema only, Schema and data, or Data only. I believe you want the last option (Data Only)
share|improve this answer
    
I think that this only works on 2008+. –  RBarryYoung Jun 29 '12 at 16:52
    
+1 Confirmed that this works on 2000 and 2005 instances using 2012 and 2008R2 SSMS. –  swasheck Jun 29 '12 at 18:23

Why not download SSMS Tools Pack from http://www.ssmstoolspack.com/Download . It easily creates insert scripts. I use it all the time and it is a fabulous tool. Did I mention it is Free!

share|improve this answer
    
It's not free anymore –  Joe Philllips Mar 3 '13 at 7:03

You can also use the bcp utility to import or export data.

In your case use something like the following command:

bcp "SELECT A, B FROM TEST" queryout Test.txt -c -T

To insert data from the file into another table:

bcp Database.Schema.Table in Test.txt -T –c

Hope this helps as an alternative

share|improve this answer

I often use a SELECT to generate other SQL:

select
    'insert dbo.TEST(A, B) values (' + convert(varchar(20), A) + ', ''' + B + ''');'
from dbo.TEST;

Save the output and re-use as needed. If column B contains text delimiters you'll have to deal with this.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.