XQuery Language Expressions
In This Chapter
- The Need for XQuery
- Why Not SQL?
- XSLT and XPath As Query Languages
- The Structure of XQuery
- Assignments with let
- Iterations with for
- Returning Results
- where Oh where?
- Ordering Up Some XQuery
- Conditional Logic
- Defining Functions
- In Brief
The Need for XQuery
When you combine XML, which is essentially an open data format independent of any specific data-formatting language, with a universal addressing mechanism such as URLs, great things happen. These two factors together make the endpoints of a transaction transparent to the kind of technologies that are on the other ends.
However, this transparency can break down in the presence of databases. Even if a database has an XML-based interface (either through SOAP or through HTTP POST or GET commands), querying that database to retrieve a dataset makes things more complicated. SQL is the standard way to make queries against most databasesbut each database vendor utilizes slightly (or not so slightly) different implementations of the SQL standard. What's worse is that the resultsets that come back are also formatted according to the whims of the database provider.
XQuery was proposed as a solution to this conundrum. To make databases truly transparent (so that it doesn't matter whether there is a Microsoft SQL Server, IBM DB2, Oracle 9i, PostgreSQL, or any other vendor's database engine), it is necessary to make a query language that will provide the following:
Platform consistencyThe language should be the same, regardless of which vendor or product is being used.
XML-centricThe language should treat non-XML databases as being equivalent to XML data stores. Note that this does not necessarily imply that the language has to be written in XML.
Set-capableSQL differs from languages such as Java or Visual Basic because it implicitly works on sets of data all at once rather than one item of data at a time. A new query language would similarly need to be set-focusedor more properly, node-focused.
Ease of useThe language should be easy enough to enable someone with a minimal database background to create complex queries.
The goal of this chapter is to examine the language in XQuery that was designed to handle all these primary points. The examples in this chapter are deliberately on the simplistic side to better illustrate the role of the command structure, but in general, XQuery finds utility more in the creation of fairly complex scripts.