tags:

views:

102

answers:

4

How can I generate some insert sql sentences using a specific select query. Are there any tool from Ms Sql Server 2008? or else?

+2  A: 

Something like this will generate a list of INSERT statements. You then copy and paste from the output and run the INSERTs. It's far from ideal, but it works.

SELECT  'INSERT table (col1, col2)
        VALUES (''' + stringcolumn + ''', ' + CAST(intcolumn AS varchar) + ')'
FROM    sourcetable
David M
this will not handle nulls and the quotes don't look to be escaped properly: `'''`
KM
The quotes **are** properly escaped, but yes, it won't handle nulls as it is - it's a quick and not comprehensive example.
David M
Example:SELECT 'INSERT WFDocTypeField (WFDocTypeID, TableName,FieldName,DMSFieldName) VALUES (' + COALESCE(CONVERT(varchar(30),WFDocTypeID),'null') + ', ''' + CAST(TableName AS varchar) + ''', ''' + CAST(FieldName AS varchar) + ''', ''' + CAST(DMSFieldName AS varchar) + ''')'FROM WFDocTypeField (nolock)WHERE WFDocTypeID = 852Thanx @David and @KM
blgnklc
A: 

Do you mean something like this?

SELECT
    'INSERT INTO MyTable (Col1, Col2, Col3) VALUES (' + Col1 + ', ' + Col2 + ', ' + Col3 + ')'
FROM
    MyTable

Of course you will need to encapsulate some fields in quotes, perform some char escaping and convert numbers to varchars, etc.

Robin Day
+1  A: 

watch out for nulls and data type conversions (SQL Server syntax):

SELECT
    'INSERT INTO YourTable (Col_int, Col_datetime, Col_varchar) VALUES ('
        +COALESCE(CONVERT(varchar(30),Col_int),'null')
        +','+COALESCE(''''+CONVERT(char(23),Col_datetime,121)+'''','null')
        +','+COALESCE(''''+Col_varchar+'''','null')
        +')'
    FROM YourTable
    WHERE ...
KM
A: 

Why do you want to do it row by row? That is a very poor technique when you can insert them all in one query. Databases are designed to perform set operations much faster than row-by-row operations.

insert table1 (field1, field2)
Select Field1, Field2 from Table2 where field3 >10
HLGEM
For creating a script that will perform the inserts on a fresh database
CRice