Sunday, August 26, 2012

Using XQuery to Query XML Data

T-SQL implements a subset of the XQuery language to query the XML data type.

The following video contains a tutorial on how to use XQuery to query XML data in SQL Server:



Below are SQL statements used in the video:

DECLARE @x xml
SET @x = '
 <Orders>
  <Order OrderID="100" OrderDate="1/30/2012">
   <OrderDetail ProductID="1" Quantity="3">
    <Price>350</Price>
   </OrderDetail>
   <OrderDetail ProductID="2" Quantity="8">
    <Price>500</Price>
   </OrderDetail>
   <OrderDetail ProductID="3" Quantity="10">
    <Price>700</Price>
   </OrderDetail>
  </Order>
  <Order OrderID="200" OrderDate="2/15/2012">
   <OrderDetail ProductID="4" Quantity="5">
    <Price>120</Price>
   </OrderDetail>
  </Order>
 </Orders>'


SELECT @x.query('/Orders')
SELECT @x.query('/Orders/Order/OrderDetail')
SELECT @x.query('/Orders/Order[1]/OrderDetail[2]')
SELECT @x.query('/Orders/Order/OrderDetail[@ProductID="2"]')
SELECT @x.query('/Orders/Order[@OrderID="100"]')
SELECT @x.query('/Orders/Order[@OrderID="100"]/OrderDetail[Price>600]')
SELECT @x.value('/Orders[1]/Order[@OrderID="100"][1]/OrderDetail[Price>600][1]', 'float')
SELECT @x.value('/Orders[1]/Order[@OrderID="200"][1]/@OrderDate', 'datetime')

1 comment: