This will depend on the data types, because you need to conditionally enclose string values ​​in quotation marks or enter numeric values ​​as strings. You also need to deal with characteristic characters:
SELECT 'INSERT INTO dbo.DestinationTable(col1, col2, col3) SELECT ' + CONVERT(VARCHAR(12), col1) + ',' + '''' + REPLACE(col2, '''', '''''') + ''',' + '''' + REPLACE(col3, '''', '''''') + ''';' FROM dbo.SourceTable;
Vyas has a rather complicated stored procedure for this purpose.
Of course, you can make it a lot easier by simply saying:
INSERT INTO OtherDatabase.dbo.DestinationTable(col1, col2, col3) SELECT col1, col2, col3 FROM dbo.SourceTable;
In other words, you don’t need to "script" paste, you can just run it ...
Aaron Bertrand Sep 22 2018-11-22T00: 00Z
source share