Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Introduction to XQuery (Part 2 of 4) : Page 2


Constants and Variables
Here's an example query that uses constant literals and variables. The following query finds the customer whose customer number is 1003 from the sample document customers.xml.

# see XQuery21.ixq in samples.zip let $custno := "1003" return document("data/customers.xml") //customer[custno=$custno]

Constants and variables are some of the most basic expressions in XQuery. Constants take of the form of literal representations of values. For example, consider the following constants:

"John Doe" 1 true "2002-05-29"

Variable references always start with a dollar sign ($), followed by the variable's name. In the preceding example, "1003" is a constant and $custno is a variable. You bind variables to values using FLWR expressions or Quantified expressions. The following example binds the results from executing a path expression (XPath expression) to a variable. It returns the list of all itemno elements in the items.xml document.

# see XQuery22.ixq in samples.zip for $i in document("data/items.xml")//item/itemno return $i

Here's another example. The following expression binds a sequence to the variable and returns the sequence. This expression also introduces the sequence constructor (the parentheses), used here to construct a sequence of two strings.

# see XQuery23.ixq in samples.zip let $i := ("s1", "s2") return $i

You can also pass variables to a function as parameters. The next example binds the sequence of nodes returned by a path expression to the variable $items, and then invokes the built-in count() function with this $items variable as a parameter. The expression therefore returns the count of item elements in the items.xml document.

# see XQuery24.ixq in samples.zip let $items:= document("data/items.xml")//item return count($items)

The variable scoping rule in XQuery is quite staightforward. The inner binding of a variable always overrides any in-scope outer binding with the same name. In other words, the most localized scope definition takes precedence. For example:

# see XQuery25.ixq in samples.zip for $s in (1 to 2) let $s := (3 to 4) return $s

The preceding query returns the sequence (3,4,3,4) because the definition of $s in the let clause overrides the $s definition in the for clause.

Comment and Contribute








