Conditional expressions
Conditional expressions use the keywords if, then, and else to evaluate one of two expressions based on whether the value of a test expression is true or false.
Syntax
- if
- The keyword that directly precedes the test expression.
- TestExpression
- An XQuery expression that determines which part of the conditional expression to evaluate.
- then
- If the effective Boolean value of TestExpression is true, then the expression that follows this keyword is evaluated. The expression is not evaluated or checked for errors if the effective Boolean value of the test expression is false.
- else
- If the effective Boolean value of TestExpression is false, then the expression that follows this keyword is evaluated. The expression is not evaluated or checked for errors if the effective Boolean value of the test expression is true.
- Expression
- Any XQuery expression. If the expression includes a top-level comma operator, then the expression must be enclosed in parentheses.
Example
In the following example, the query
constructs a list of
product
elements that include
an attribute named basic
. The value of the basic
attribute
is specified conditionally based on whether the value of the price
element
is less than 10:for $prod in db2-fn:xmlcolumn('PRODUCT.DESCRIPTION')/product/description
return (
if (xs:decimal($prod/price) < 10)
then <product basic = "true">{fn:data($prod/name)}</product>
else <product basic = "false">{fn:data($prod/name)}</product>)
The
query returns the following result:<product basic="true">Snow Shovel, Basic 22"</product>
<product basic="false">Snow Shovel, Deluxe 24"</product>
<product basic="false">Snow Shovel, Super Deluxe 26"</product>
<product basic="true">Ice Scraper, Windshield 4" Wide</product>
In
this example, the test expression constructs an xs:decimal value
from the value of the price
element. The xs:decimal function
is used to force a decimal comparison.