Create SQL INSERT Script with values gathered from table

后端 未结 5 1300
迷失自我
迷失自我 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:38

    You can do this with SSMS.

    1 - Right-click your database in Object Explorer.
    2 - Select Tasks/Generate Scripts...
    3 - On the Set Scripting Options page, click the Advanced button and make sure Types of data to script is set to Data only.

    The resulting script will have a USE DATABASE statement at the top. Change this to the database you would like to insert the data into.

    0 讨论(0)
  • 2020-12-08 06:40

    Use the free SSMS tools pack to "generate insert statements"?

    Or in SSMS (don't have it on this PC to confirm) the export wizards allows you to "script data" too

    0 讨论(0)
  • 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...

    0 讨论(0)
  • 2020-12-08 07:01

    @RedFilter, your solution is working like a charm for less data SIZE.

    In my case, When I tried to open the Exported sql file, I faced the OutOfMemoryException.

    The file size is around 4GB.

    In order to get the data from that file, I tried BCP(Bulk Copy Program) approach.

    Hope that would be help full for someone.

    0 讨论(0)
  • 2020-12-08 07:04

    use the INSERT INTO ... SELECT format:

    http://blog.sqlauthority.com/2007/08/15/sql-server-insert-data-from-one-table-to-another-table-insert-into-select-select-into-table/

    0 讨论(0)
提交回复
热议问题