Linked Server Insert-Select Performance

后端 未结 6 628
时光取名叫无心
时光取名叫无心 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:25

    If you must push data from the source to the target (e.g., for firewall or other permissions reasons), you can do the following:

    In the source database, convert the recordset to a single XML string (i.e., multiple rows and columns combined into a single XML string). Then push that XML over as a single row (as a varchar(max), since XML isn't allowed over linked databases in SQL Server).

        DECLARE @xml XML
    
        SET @xml = (select * from SourceTable FOR XML path('row'))
    
        Insert into TempTargetTable values (cast(@xml AS VARCHAR(max)))
    

    In the target database, cast the varchar(max) as XML and then use XML parsing to turn that single row and column back into a normal recordset.

    DECLARE @X XML = (select '' + ImportString + '' from TempTargetTable)
    
    DECLARE @iX INT
    EXEC sp_xml_preparedocument @ix output, @x
    
    insert into TargetTable
    SELECT [col1],
           [col2]
    FROM OPENXML(@iX, '//row', 2) 
    WITH ([col1] [int],
           [col2] [varchar](128)
    )
    
    EXEC sp_xml_removedocument @iX
    

提交回复
热议问题