Skip to Content
XQuery
book

XQuery

by Priscilla Walmsley
March 2007
Intermediate to advanced content levelIntermediate to advanced
512 pages
21h 15m
English
O'Reilly Media, Inc.
Content preview from XQuery

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.

Syntax of a variable declarationThe optional as clause, useful for static typing, is described in "Type Declarations in Global Variable Declarations" in Chapter 14.

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

XQuery, 2nd Edition

XQuery, 2nd Edition

Priscilla Walmsley
XPath and XPointer

XPath and XPointer

John Simpson
XQuery Kick Start

XQuery Kick Start

James McGovern, Per Bothner, Kurt Cagle, James Linn, Vaidyanathan Nagarajan
Learning XSLT

Learning XSLT

Michael Fitzgerald

Publisher Resources

ISBN: 0596006349Supplemental ContentErrata