Advertisement
Intermediate SQL Server, XML Data Type & Querying

How do you use the query and nodes methods to work with repeating elements within an XML document, such as a list of items in an order?

Short answer

The nodes method shreds an XML document into a rowset based on a specified XPath, effectively creating one row for each matching element, which you can then combine with CROSS APPLY to extract individual values from each of those repeating elements using the value method…

Save SQL Server mock interview
Advertisement
AModel answer
The nodes method shreds an XML document into a rowset based on a specified XPath, effectively creating one row for each matching element, which you can then combine with CROSS APPLY to extract individual values from each of those repeating elements using the value method, letting you convert a nested XML structure into a normal relational result set.
SELECT OrderId,
  T.item.value('(name)[1]', 'VARCHAR(100)') AS ItemName,
  T.item.value('(quantity)[1]', 'INT') AS Quantity
FROM Orders
CROSS APPLY OrderDetails.nodes('/order/items/item') AS T(item);
Real-world example
An order processing system extracts each individual line item from an XML order document using nodes and CROSS APPLY, converting the nested XML structure into a clean set of relational rows for further processing.
Likely follow-ups
  • What is the difference between the query method and the value method?
  • Can nodes handle deeply nested XML structures with multiple levels?
Related topics