Tuesday, June 26, 2007

Generate insert statement from sql query

Generate insert statement from sql query
=================================


In some case you might have a requirement where you might want to generate insert statments directly by firing a sql query. I am sure you might need to use this especially for those who are into maintainance related work.

Anyway here is the process:

You might want to create a table : (I am assuming that you are already having a table)

create table myTable (
Id int,
name nvarchar(200))

select * from myTable


Insert some data into the table : (I am assuming that you are already having data into table)

insert into myTable values(1,'kingkong')
insert into myTable values(2,'godzilla')


Here is the main sql statement which generates the sql. The logic is straigh forward. Just to insert single quotes you might need to add '''' .. just change the query as per your own requirement



select convert(varchar(1000),'insert into myTable values(' + convert(varchar(10),Id) + ',' + '''' + convert(varchar(100),Name) + '''' + ')') from myTable

Result: (listing all the insert statement for a given table)

insert into myTable values(1,'kingkong')
insert into myTable values(2,'godzilla')


Same way like above you might want to generate custom update statement as well. You can also try it out by yourself

No comments: