将XML数据分解为SQL行时保留元素顺序

时间:2012-04-16 09:42:50

标签: sql sql-server-2005 xquery

在SQL Server视图中将XML分解为行时,如何返回元素序列?

示例输入:

<ol>
  <li>Smith</li>
  <li>Jones</li>
  <li>Brown</li>
</ol>

期望的输出:

Sequence  Name
--------  -----------
    1     Smith
    2     Jones
    3     Brown

现有观点:

CREATE VIEW OrderedList
AS
SELECT [Sequence] = CAST(NULL AS int)   -- TODO: Get ordinal position
       [Name] = b.b.value('.', 'nvarchar(max)')
FROM
(
    SELECT a = CAST('<ol><li>Smith</li><li>Jones</li><li>Brown</li></ol>' AS xml)
) a
CROSS APPLY a.a.nodes('/ol/li') b (b)

1 个答案:

答案 0 :(得分:11)

您可以在xml节点上使用row_number()

CREATE VIEW OrderedList
AS
SELECT [Sequence] = ROW_NUMBER() OVER(ORDER BY b.b),
       [Name] = b.b.value('.', 'nvarchar(max)')
FROM
(
    SELECT a = CAST('<ol><li>Smith</li><li>Jones</li><li>Brown</li></ol>' AS xml)
) a
CROSS APPLY a.a.nodes('/ol/li') b (b)

Ref:Uniquely Identifying XML Nodes with DENSE_RANK 作者:Adam Machanic。