Variable references
A variable reference is an NCName that is preceded by a dollar sign ($). When a query is evaluated, each variable reference resolves to the value that is bound to the variable. Every variable reference must match a name in the in-scope variables at the point of reference.
Variables are added to the in-scope variables in the following ways:
- A variable can be added to the in-scope variables by the host language environment, SQL/XML, through the XMLQUERY function, the XMLTABLE function, or the XMLEXISTS predicate. A variable that is added by SQL/XML is in scope for the entire query unless the variable is overridden by another binding of the same variable in an XQuery expression.
- A variable can be bound to a value by an XQuery expression. The kinds of expressions that can
bind variables are FLWOR expressions and quantified expressions. Function calls also bind values to
the formal parameters of functions before executing the function body. A variable that is bound by
an XQuery expression is in scope throughout the expression in which it is bound.A variable name cannot be declared more than once in a FLWOR expression. For example, Db2 XQuery does not support the following expression:
for $i in (1, 2) for $i in ("a", "b") return $i
If a variable reference matches two or more variable bindings
that are in scope, then the reference refers to the inner binding
(the binding whose scope is smaller).
Tip: To make your
code easier to read, use unique names for variables within a query.
Example
In the following example, a FLWOR
expression binds the variable
$seq to the sequence
(10, 20, 30):let $seq := (10, 20, 30)
return $seq[2];The returned value is 20.