Tuesday, February 14, 2012

Create a SQL insert statement(s) from a SQL select statement

I'm not sure why, but porting a SQL Server 2008 DB to PostGres has been a pain in the ass. I would think MS would have a simple SQL export command that would generate a script that could be used by another DB to create a new DB with the same data, but no.

A coworker showed me this trick to create INSERT statements from SELECT statements to help me out, though

select 'insert into mugg.subscription(subscription_id, name, system) values (''' || subscription_id || ',' || name || ',' || system ||''')' from mugg.subscription

After running this, Here is one of the rows:
"insert into mugg.subscription(subscription_id, name, system) values ('6CBF39EE-0E53-4CED-841E-02EC0A8E8C00,i-cubed testing subscription,MUGG')"

The pipes (||) are SQL's way of concatenating strings and you use a single quote to escape a single quote.

No comments:

Post a Comment