Reputation: 4954
I'd like to know if it is possible to check the existence of a variable in XQuery. I mean to know if the variable is defined or bound. Some sort of a if (defined($a))
.
I have searched on the Internet and a little bit in the XQuery spec without success.
Upvotes: 1
Views: 2210
Reputation: 38712
Undefined variables names are checked in a static analysis phase (let's call it "at compile time" here).
From the W3C XQuery 1.0 Recommendation (similarly applies to XQuery 3.0):
During the static analysis phase, the query is parsed into an internal representation [...]. A parse error is raised as a static error [err:XPST0003]. The static context is initialized by the implementation (step SQ2). [...] The static context is used to resolve schema type names, function names, namespace prefixes, and variable names (step SQ4). If a name of one of these kinds in the operation tree is not found in the static context, a static error ([err:XPST0008] or [err:XPST0017]) is raised [...].
external
VariablesThe only exception applies to variables defined as external using
declare variable $var external;
In this case, a dynamic error will be thrown (again cited from the XQuery Recommendation):
A reference to a variable that was declared external, but was not bound to a value by the external environment, raises a dynamic error [err:XPDY0002].
external
Variables Are BoundI'm not aware of a possibility to check at runtime whether an external variable actually is bound, but in XQuery 3.0 you could use try/catch to test this:
xquery version '3.0';
declare variable $var external;
try { $var }
catch err:XPDY0002
{ "External variable not bound!" }
Upvotes: 2
Reputation: 16917
No, that is not possible.
Accessing an undefined variable is a static error, which is raised during the parsing/compiling of the expression.
Upvotes: 1