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
2010-04-27 12:59:27
this will not handle nulls and the quotes don't look to be escaped properly: `'''`
KM
2010-04-27 13:13:26
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
2010-04-27 13:28:13
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
2010-04-27 13:35:39
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
2010-04-27 13:01:25
+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
2010-04-27 13:05:43
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
2010-04-27 13:30:10