How can I find the order of nodes in an XML document?
What I have is a document like this:
SQL Server's row_number() actually accepts an xml-nodes column to order by. Combined with a recursive CTE you can do this:
declare @Xml xml =
'
'
;with recur as (
select
ordr = row_number() over(order by x.ml),
parent_code = cast('' as varchar(255)),
code = x.ml.value('@code', 'varchar(255)'),
children = x.ml.query('./value')
from @Xml.nodes('value') x(ml)
union all
select
ordr = row_number() over(order by x.ml),
parent_code = recur.code,
code = x.ml.value('@code', 'varchar(255)'),
children = x.ml.query('./value')
from recur
cross apply recur.children.nodes('value') x(ml)
)
select *
from recur
where parent_code = '121'
order by ordr
As an aside, you can do this and it'll do what do you expect:
select x.ml.query('.')
from @Xml.nodes('value/value')x(ml)
order by row_number() over (order by x.ml)
Why, if this works, you can't just order by x.ml directly without row_number() over is beyond me.