Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve element order when shredding XML data into SQL rows

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)
like image 938
Anthony Faull Avatar asked Apr 16 '12 09:04

Anthony Faull


People also ask

How do I filter XML data in SQL Server?

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.

What is shredding XML?

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.

Which technique can you use to read XML from SQL Server?

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.


1 Answers

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.

like image 87
Mikael Eriksson Avatar answered Oct 01 '22 20:10

Mikael Eriksson