Flattening hierarchical XML in SQL using the nodes() method

前端 未结 1 459
清酒与你
清酒与你 2021-02-10 03:50

I have a Stored Procedure that takes an XML document as a parameter similar in a structure to the following:


  

        
相关标签:
1条回答
  • 2021-02-10 03:57

    I seem to have answered my own question after a bit more looking around online:

    SELECT
        grandparent.gname.value('@name', 'VARCHAR(15)'),
        parent.pname.value('@name', 'VARCHAR(15)'),
        child.cname.value('@name', 'VARCHAR(15)')
    FROM
        @xmlFamilyTree.nodes('/grandparent') AS grandparent(gname)
    CROSS APPLY
        grandparent.gname.nodes('*') AS parent(pname)
    CROSS APPLY
        parent.pname.nodes('children/*') AS child(cname)
    

    Using CROSS APPLY I can select the top-level grandparent node and use this to select the child parent nodes and so on. Using this method I have taken my query from executing in around 1 minute 30 seconds down to around 6 seconds.

    Interestingly though, if I use the "old" OPEN XML method to retrieve the same data, the query executes in 1 second!

    It seems like you may have to approach the use of these two techniques on a case-by-case basis depending on the expected size/complexity of the document being passed in.

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