There is a way within XQuery to return the position of the current node: you can count all nodes previous to it
SELECT T.X.value('text()[1]', 'nvarchar(100)') as RowLabel,
T.X.value('let $i := . return count(/Rows/Row[. << $i]) + 1', 'int') as RowNumber
FROM @xml.nodes('/Rows/Row') as T(X);
What this does is:
- Assign the current node to the variable
$i
- Takes all the nodes in
/Rows/Row
that are previous to $i
and counts them
- Then add 1 to make it one-based
In some situations you may not want to go back to the root node, in which case you can use the ..
parent axis
SELECT T.X.value('text()[1]', 'nvarchar(100)') as RowLabel,
T.X.value('let $i := . return count(../Row[. << $i]) + 1', 'int') as RowNumber
FROM @xml.nodes('/Rows/Row') as T(X);
You can also count backwards from the end by changing to >>
.
dbfiddle