How can I find the order of nodes in an XML document?
What I have is a document like this:
<value code="1">
<value code="11">
<value code="111"/>
</value>
<value code="12">
<value code="121">
<value code="1211"/>
<value code="1212"/>
</value>
</value>
</value>
and I'm trying to get this thing into a table defined like
CREATE TABLE values(
code int,
parent_code int,
ord int
)
Preserving the order of the values from the XML document (they can't be ordered by their code). I want to be able to say
SELECT code
FROM values
WHERE parent_code = 121
ORDER BY ord
and the results should, deterministically, be
code
1211
1212
I have tried
SELECT
value.value('@code', 'varchar(20)') code,
value.value('../@code', 'varchar(20)') parent,
value.value('position()', 'int')
FROM @xml.nodes('/root//value') n(value)
ORDER BY code desc
But it doesn't accept the position()
function ('position()
' can only be used within a predicate or XPath selector).
I guess it's possible some way, but how?