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)
XQuery in the SQL Server helps to query and extract data from XML documents. XQuery gives different approaches to get information from the XML document and the equivalent can be used on applying a data filter or where clause on XML elements as well.
XML shredding is the process of extracting values from XML documents and using them to update tables in the database. This is done based on a user-defined mapping specification that maps the XML structure to the target tables.
Read the XML file using OPENROWSET, and save the data in the table. In the below code, we create a table for our raw XML data. Then read the XML file and save the same data into the "PointsXML" table. CREATE TABLE PointsXML -- Create table for raw XML file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With