Wednesday, January 10, 2007

Generating SQL Insert Statements From A Data Table

Every now and then one is faced with a situation where they have to write and execute insert statements with existing tables and data. Having to personally deal with this before, a friend of mine shed some light as to how to generate SQL Insert statements. This comes in handy when you may not have access to tools, such as Microsoft's Enterprise Manager for SQL server or of the sort. Below is an example of such a solution.

The following is a simple example, but it can be used as a guide to generate various queries.

select('Insert into TableName + '(' + TableColumnName1,TableColumnName2,TableColumnName3 + ')' + values(''' + TableColumnName1 + ''',''' + TableColumnName2 + ''',''' + TableColumnName3 + ''')') from TableName

The basic principle is concatenating strings. The text in italics serve as parameters, which represent your table's name and columns.

In my case, I used this to generate an insert statment for each row in a static table. The output to this looked something like the following.

Insert into TableName (TableColumnName1, TableColumnName2, TableColumnName3) values(' TableColumnName1','TableColumnName2','TableColumnName3') from TableName

As simple as this may seem, there's a few things to consider.

  • After you run this script, if you have data that contains appostrophies, you will need to manually add the proper set of single quotes to the output in order to escape those characters.

  • The opposite is true when dealing with Integer types. You don't need to add the single quotes within the script. Update The example as is will not work for Integers or any other type other then varchars. You will encounter an invalid casting message. I have yet to solve this one as well.

  • This will not work with tables that contain nulls. The script will abend once it encounters nulls.

If anyone can post a solution to this, I would highly appreciate it.