问题
How to get the row number for the rows using SQL Server 2012?
Here is the xml
<Rows>
<Row>Coating</Row>
<Row>Drying</Row>
<Row>Waxing</Row>
</Rows>
I need data returned like this
RowLabel RowNumber
-------------------
Coating 1
Drying 2
Waxing 3
回答1:
You can use some internal knowledge about how SQL Server implements XML shredding and use row_number()
like this.
declare @XML xml =
'<Rows>
<Row>Coating</Row>
<Row>Drying</Row>
<Row>Waxing</Row>
</Rows>'
select T.X.value('text()[1]', 'nvarchar(100)') as RowLabel,
row_number() over(order by T.X) as RowNumber
from @XML.nodes('/Rows/Row') as T(X)
Ref: Uniquely Identifying XML Nodes with DENSE_RANK
Or you can "play it safe" and use a numbers table.
select T.X.value('text()[1]', 'nvarchar(100)') as RowLabel,
N.Number as RowNumber
from Numbers as N
cross apply @XML.nodes('/Rows/Row[sql:column("N.Number")]') as T(X)
where N.Number between 1 and @XML.value('count(/Rows/Row)', 'int')
来源:https://stackoverflow.com/questions/23836226/get-the-position-of-xml-element-in-sql-server-2012