How can I find the order of nodes in an XML document?
What I have is a document like this:
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