Variable Declarations
Variables can optionally be declared (and bound) in the query prolog. If a variable is bound within an expression in the query body, it does not have to be declared in the prolog as well. For example, you can use the expression let $myInt := 2
in the query body without declaring
$myInt
in advance. $myInt
is bound when the let
expression is evaluated.
However, it is sometimes necessary to declare variables in the prolog, such as when:
They are referenced in a function that is declared in that module
They are referenced in other modules that import the module
Their value is set by the processor outside the scope of the query
Declaring variables in the prolog can also be a useful way to define constants, or values that can be calculated up front and used throughout the query. It's important to remember that global variables (prolog-declared variables) are immutable, just like other XQuery variables.
Variable Declaration Syntax
The syntax of a variable declaration is shown in Figure 12-4. For example, the declaration:
declare variable $maxItems := 12;
binds the value 12
to the variable $maxItems
.
Figure 12-4. Syntax of a variable declaration[a]
Important
A previous draft of the XQuery recommendation specified the following syntax for variable declarations:
define variable $maxItems {12}
Some popular XQuery implementations still use this old syntax.
The Scope of Variables ...
Get XQuery now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.