Microsoft® SQL Server® 2012 Bible

(Ben Green) #1

360


Part III: Advanced T-SQL Data Types and Querying Techniques


<row OrderNumber="10003" OrderDate="2011-06-17T00:00:00" Name="Scott" />
<row OrderNumber="10004" OrderDate="2011-06-18T00:00:00" Name="Adam" />
*/

The RAW directive also enables you to specify an optional ROOT directive (similar to the
AUTO directive), which generates a root element with the specifi ed name.

SELECT o.OrderNumber, o.OrderDate, c.Name
FROM Orders o
INNER JOIN Customer c ON o.CustomerID = c.CustomerID
FOR XML RAW('Order'), ROOT('Orders')

/*
<Orders>
<Order OrderNumber="10001" OrderDate="2011-06-15T00:00:00" Name="Scott" />
<Order OrderNumber="10002" OrderDate="2011-06-16T00:00:00" Name="Adam" />
<Order OrderNumber="10003" OrderDate="2011-06-17T00:00:00" Name="Scott" />
<Order OrderNumber="10004" OrderDate="2011-06-18T00:00:00" Name="Adam" />
</Orders>
/*

If you specify the ROOT directive without including a name for the ROOT element, a
top-level root element named <root> generates.

The RAW directive also accepts the ELEMENTS directive:

SELECT o.OrderNumber, o.OrderDate, c.Name
FROM Orders o
INNER JOIN Customer c ON o.CustomerID = c.CustomerID
FOR XML RAW('Order'), ROOT('Orders'), ELEMENTS

/*
<Orders>
<Order>
<OrderNumber>10001</OrderNumber>
<OrderDate>2011-06-15T00:00:00</OrderDate>
<Name>Scott</Name>
</Order>
<Order>
<OrderNumber>10002</OrderNumber>
<OrderDate>2011-06-16T00:00:00</OrderDate>
<Name>Adam</Name>
</Order>
<Order>
<OrderNumber>10003</OrderNumber>
<OrderDate>2011-06-17T00:00:00</OrderDate>
<Name>Scott</Name>
</Order>
<Order>
<OrderNumber>10004</OrderNumber>
<OrderDate>2011-06-18T00:00:00</OrderDate>

c14.indd 360c14.indd 360 7/30/2012 4:49:03 PM7/30/2012 4:49:03 PM


http://www.it-ebooks.info
Free download pdf