tags:

views:

66

answers:

4

I have a bunch of records I want to move to another database and I just want to create a bunch of inserts that I can copy and paste. I've seen someone do this before but I can't figure it out. I'm not getting the escapes right.

It's something like this where 'Code', 'Description' and 'Absent' are the columns I want from the table.

 SELECT 'INSERT INTO AttendanceCodes
          (Code, Description, Absent) 
         VALUES 
          (' + Code + ',' + Description  + ',' + Absent')'
  FROM AttendanceCodes 

The end result should be a slew of INSERTS with the correct values like this:

 INSERT INTO AttendanceCodes 
   (Code, Description, Absent) 
 VALUES 
   ('A','Unverified Absence','UA')
+2  A: 

Check this

SELECT 'INSERT INTO AttendanceCodes (Code, Description, Absent) VALUES (''' + Code + ''',''' + Description  + ''',''' + Absent''')' 
  FROM AttendanceCodes  
Kronass
i would add a `N` before each value to make sure unicode text ( *if present* ) gets copied correctly in the new database...
Gaby
Perfect. My only question is, how did you respond so fast? Geesh!
Mikecancook
+2  A: 

try something like this:

 SELECT 
    'INSERT INTO AttendanceCodes (Code, Description, Absent) VALUES (' 
        + ISNULL(''''+CONVERT(varchar(8000),Code)+'''','null')
        + ',' 
        + ISNULL(''''+CONVERT(varchar(8000),Description)+'''','null')
        + ',' 
        + ISNULL(''''+CONVERT(varchar(8000),Absent)+'''','null')
        +')'
    FROM AttendanceCodes 

This will handle NULLs. I'm not sure of your columns data types, but you can only concatenate strings, so I forced everything to varchar(8000), you can modify this as necessary.

KM
This is definitely a more thorough solution but it's more than what I need. Thanks!
Mikecancook
I rarely concatenate a string without considering NULLS and data type, get in the habit and you'll have fewer data type conversion errors and null strings that should contain a value to debug.
KM
A: 

A useful SSMS addin to generate this sort of script is SSMS Tool Pack http://www.ssmstoolspack.com/

Martin Smith
A: 

For a generic stored procedure that takes a table name (and some other options) and generates insert statements for current data in that table, check out this handy link.

It creates a procedure called sp_generate_inserts. You pass this procedure the table name, and it will generate all the insert statements to recreate the data.

Sylvia