Service Broker — how to extract the rows from the XML message?

后端 未结 2 1627
野的像风
野的像风 2021-01-14 19:45

Say I have the following situation (for demonstration). The simple table content is converted to an XML value and sent via Service Broker to another SQL server where the res

相关标签:
2条回答
  • 2021-01-14 20:16
    CREATE TABLE tab (a int, b int, c int); 
    GO 
    
    INSERT INTO tab (a, b, c) VALUES (1, 11, 111); 
    INSERT INTO tab (a, b, c) VALUES (2, 22, 222); 
    INSERT INTO tab (a, b, c) VALUES (3, 33, 333); 
    INSERT INTO tab (a, b, c) VALUES (4, 44, 444); 
    GO 
    
    CREATE TABLE tab_destination (a int, b int, c int); 
    go
    
    declare @x xml = (SELECT * FROM tab FOR XML RAW, TYPE); 
    
    insert into tab_destination (a, b, c)
    select 
        x.value('@a', 'int'),
        x.value('@c', 'int'),
        x.value('@b', 'int')
        from @x.nodes('//row') t(x);
    GO 
    
    select * from tab_destination;
    go
    

    Time to read xml Data Type Methods

    0 讨论(0)
  • 2021-01-14 20:26

    And other option (i would prefer Remus Rusanu example though.. If a lots of columns and table structures are the same, this helps get lazy):

    declare @x xml = (SELECT * FROM tab FOR XML RAW, root('tab'), TYPE); 
    
    Declare @docHandle int  
    EXEC sp_xml_preparedocument @docHandle OUTPUT, @x
    
    Select *
    FROM OPENXML(@docHandle, 'tab//', 1) 
    With dbo.Tab
    
    EXEC sp_xml_removedocument @docHandle
    
    0 讨论(0)
提交回复
热议问题