5

How do I return the element sequence when shredding XML into rows in a SQL Server view?

Sample Input:

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

Desired output:

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

Existing view:

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)
0

1 Answer 1

11

You can use row_number() on the xml node.

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 by Adam Machanic.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.