Finding node order in XML document in SQL Server

前端 未结 6 1403
死守一世寂寞
死守一世寂寞 2020-12-01 04:41

How can I find the order of nodes in an XML document?

What I have is a document like this:


    
            


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 05:15

    According to this document and this connect entry it is not possible, but the Connect entry contains two workarounds.

    I do it like this:

    WITH n(i) AS (SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9),
         o(i) AS (SELECT n3.i * 100 + n2.i * 10 + n1.i FROM n n1, n n2, n n3)
    SELECT v.value('@code', 'varchar(20)') AS code,
           v.value('../@code', 'varchar(20)') AS parent,
           o.i AS ord
      FROM o
     CROSS APPLY @xml.nodes('/root//value[sql:column("o.i")]') x(v)
     ORDER BY o.i
    

提交回复
热议问题