15.02.2015 Views

C# 4 and .NET 4

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

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

XMl Data Type ❘ 977<br />

data(/Exam[1]/@Number) . data() is an XQuery function that returns the value of the node specifi ed with<br />

the argument. The node /Exam[1] is used to access the fi rst element; @Number specifi es the XML<br />

attribute Number . The text within the element < Number > is defi ned from the variable $course .<br />

Contrary to <strong>C#</strong>, where the fi rst element in a collection is accessed with an index of 0,<br />

with XPath the fi rst element in a collection is accessed with an index of 1.<br />

The result of this query is shown here:<br />

< Course ><br />

< Exam > 70-562 < /Exam ><br />

< Number > 2310 < /Number ><br />

< /Course ><br />

< Course ><br />

< Exam > 70-562 < /Exam ><br />

< Number > 6463 < /Number ><br />

< /Course ><br />

You can change the XQuery statement to also include a where clause for fi ltering XML elements. The<br />

following example only returns courses from the XML column if the course number has a value higher<br />

than 2562:<br />

SELECT [Info].query('<br />

for $course in /Exam/Course<br />

where ($course > 2562)<br />

return<br />

< Course ><br />

< Exam > { data(/Exam[1]/@Number) } < /Exam ><br />

< Number > { data($course) } < /Number ><br />

< /Course > ')<br />

AS Course<br />

FROM [Exams]<br />

WHERE Id=2<br />

The result is reduced to just one course number:<br />

< Course ><br />

< Exam > 70-562 < /Exam ><br />

< Number > 6463 < /Number ><br />

< /Course ><br />

XQuery in SQL Server allows using several other XQuery functions for getting minimum, maximum, or<br />

summary values, working with strings, numbers, checking for positions within collections, <strong>and</strong> so on.<br />

The next example shows the use of the count() function to get the number of /Exam/Course elements:<br />

SELECT [Id], [Number], [Info].query('<br />

count(/Exam/Course)')<br />

AS "Course Count"<br />

FROM [Exams]<br />

The data returned displays the number of courses for the exams:<br />

Id Number Course Count<br />

1 70-502 1<br />

2 70-562 2<br />

3 70-561 2<br />

Xml data modification language (Xml dml)<br />

XQuery, as it is defi ned by the W3C ( http://www.w3c.org ), allowed only querying of data when Microsoft<br />

implemented XQuery in SQL Server 2005. Because of this XQuery restriction, Microsoft defi ned an<br />

extension to XQuery that has the name XML Data Modifi cation Language (XML DML).<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!