17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 16: A Brief XML Primer<br />

If, for example, we wanted to know the value of the LaborHours attribute in the first Location element<br />

for ProductModelID 66, we might write something like:<br />

WITH XMLNAMESPACES (‘http://schemas.microsoft.com/sqlserver/2004/07/<br />

adventure-works/ProductModelManuInstructions’ AS PI)<br />

SELECT ProductModelID,<br />

Instructions.value(‘(/PI:root/PI:Location/@LaborHours)[1]’,<br />

‘decimal (5,2)’) AS Location<br />

FROM Production.ProductModel<br />

WHERE ProductModelID = 66;<br />

Note that the URL portion of the namespace declaration must be entered on a single line. They are<br />

shown here word wrapped onto multiple lines because there is a limit to the number of characters we<br />

can show per line in print. Make sure you include the entire URL on a single line.<br />

Check the results:<br />

ProductModelID Location<br />

-------------- ---------------------------------------<br />

66 1.50<br />

(1 row(s) affected)<br />

Note that <strong>SQL</strong> <strong>Server</strong> has extracted just the specified attribute value (in this case, the LaborHours attribute<br />

of the Location node) as a discrete piece of data. The data type of the returned values must be<br />

castable into a non-XML type in <strong>SQL</strong> <strong>Server</strong>, and must return a scalar value — that is, you cannot have<br />

multiple rows.<br />

.modify<br />

494<br />

Ah, here things get just a little interesting.<br />

XQuery, left in its standard W3C form, is a read-only kind of thing — that is, it is great for selecting data<br />

but offers no equivalents to INSERT, UPDATE, or DELETE. Bummer deal! Well, <strong>Microsoft</strong> is apparently<br />

having none of that and has done its own extension to XQuery to provide data manipulation for XQuery.<br />

This extension to XQuery is called XML Data Manipulation Language, or XML DML. XML DML adds<br />

three new commands to XQuery:<br />

❑ insert<br />

❑ delete<br />

❑ replace value of<br />

Note that these new commands, like all XML keywords, are case sensitive.<br />

Each of these does what it implies, with replace value of taking the place of <strong>SQL</strong>’s UPDATE statement.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!