Linked Server Insert-Select Performance

后端 未结 6 581
时光取名叫无心
时光取名叫无心 2021-01-02 17:30

Assume that I have a table on my local which is Local_Table and I have another server and another db and table, which is Remote_Table (table struct

6条回答
  •  一生所求
    2021-01-02 18:27

    The fastest way is to pull the data rather than push it. When the tables are pushed, every row requires a connection, an insert, and a disconnect.

    If you can't pull the data, because you have a one way trust relationship between the servers, the work around is to construct the entire table as a giant T-SQL statement and run it all at once.

    DECLARE @xml XML
    
    SET @xml = (
            SELECT 'insert Remote_Table values (' + '''' + isnull(first_col, 'NULL') + ''',' +
                -- repeat for each col
                '''' + isnull(last_col, 'NULL') + '''' + ');'
            FROM Local_Table
            FOR XML path('')
            ) --This concatenates all the rows into a single xml object, the empty path keeps it from having   wrapped arround each value
    
    DECLARE @sql AS VARCHAR(max)
    
    SET @sql = 'set nocount on;' + cast(@xml AS VARCHAR(max)) + 'set nocount off;' --Converts XML back to a long string
    
    EXEC ('use RemoteDb;' + @sql) AT RemoteServer
    

提交回复
热议问题