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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

7 30 1.00<br />

7 45 0.50<br />

7 50 3.00<br />

7 60 4.00<br />

10 10 2.00<br />

10 20 1.50<br />

10 30 1.00<br />

10 4 1.50<br />

10 50 3.00<br />

10 60 4.00<br />

43 50 3.00<br />

44 50 3.00<br />

47 10 1.00<br />

47 20 1.00<br />

47 50 3.50<br />

48 10 1.00<br />

48 20 1.00<br />

48 50 3.50<br />

53 50 0.50<br />

66 50 1.75<br />

67 50 1.00<br />

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

As you can see, we are getting back multiple rows for many of what were originally a single row in the<br />

ProductModel table. For example, ProductModelID 7 had six different instances of the Location element,<br />

so we received six rows instead of just the single row that existed in the ProductModel table.<br />

While this is, perhaps, the most complex of the various XML data type methods, the power that it gives<br />

you to transform XML data for relational use is virtually limitless.<br />

.exist<br />

.exist works something like the EXISTS statement in <strong>SQL</strong>. It accepts an expression (in this case, an<br />

XQuery expression rather than a <strong>SQL</strong> expression) and will return a Boolean indication of whether the<br />

expression was true or not. (NULL is also a possible outcome.)<br />

If, in our .modify example, we had wanted to show rows that contain steps that had spec elements, we<br />

could have used .exist:<br />

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

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

SELECT ProductModelID, Instructions<br />

FROM Production.ProductModel<br />

WHERE Instructions.exist(‘/PI:root/PI:Location/PI:step/PI:specs’) = 1<br />

Pay particular attention to the point at which the test condition is being applied!<br />

Chapter 16: A Brief XML Primer<br />

For example, the code would show us rows where at least one step had a spec element in it — it does not<br />

necessarily require that every step have the spec element. If we wanted every element to be tested, we<br />

would either need to pull the elements out as individual rows (using .nodes) or place the test condition<br />

in the XQuery.<br />

497

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

Saved successfully!

Ooh no, something went wrong!