Create SQL INSERT Script with values gathered from table

后端 未结 5 1307
迷失自我
迷失自我 2020-12-08 06:17

I need to create a INSERT script in order to insert in another database the same data.
If in SQL Server I select \"Script table as > INSERT To\" I can easily recreate t

5条回答
  •  青春惊慌失措
    2020-12-08 06:59

    It will depend on the data types, because you need to conditionally enclose string values in quotes or cast numeric values as strings. You also need to deal with problem characters:

    SELECT 'INSERT INTO dbo.DestinationTable(col1, col2, col3) 
        SELECT ' + CONVERT(VARCHAR(12), col1) + ',' 
            + '''' + REPLACE(col2, '''', '''''') + ''','
            + '''' + REPLACE(col3, '''', '''''') + ''';'
        FROM dbo.SourceTable;
    

    Vyas has a pretty complex stored procedure for this purpose.

    Of course you can do this much easier by just 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" an insert, you can just run it...

提交回复
热议问题