How do I iterate through the Nodes of a XML Field in T-SQL?

后端 未结 2 1392
谎友^
谎友^ 2020-12-16 01:54

I have an XML field that I know will have at least one \"ChildNode\" in it, but possibly more. I am trying to make a loop in T-SQL that will get the XML of each ChildNode a

相关标签:
2条回答
  • 2020-12-16 02:35

    I don't have any idea what your XML looks like, but you probably have to use a different approach - don't try to iterate and loop and stuff like that - instead use the .nodes() function in XQuery:

    SELECT 
        Child.value('(SomeElement)[1]', 'int'),
        Child.value('(SomeOtherElement)[1]', 'Varchar(50)')
    FROM
        XMLField.nodes("/RootNode/ParentNode/ChildNode") AS N(Child)
    

    That basically leaves the iterating / looping to XQuery and you don't have to mess around with indices or anything like that at all.....

    0 讨论(0)
  • 2020-12-16 02:43

    There still could be a need to query sub elements which the answer to this question would not solve. You can just use sql:variable to satisfy nodes() requirement of a string literal argument to query sub elements of a specific node iteratively.

    DECLARE @iterator = 1
    
    SELECT 
        Child.value('(SomeElement)[1]', 'int'),
        Child.value('(SomeOtherElement)[1]', 'Varchar(50)'),
    FROM
        XMLField.nodes("/RootNode/ParentNode[sql:variable("@iterator")]/ChildNode") AS N(Child)
    
    0 讨论(0)
提交回复
热议问题