DB2 10.5 for Linux, UNIX, and Windows
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--(--TestExpression--)--then--Expression--else--Expression-><
- 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.
- If either the then or else condition branch contains an updating expression, then the conditional expression is an updating expression. An updating expression must be within the modify clause of a transform expression.
- For an updating conditional expression, each branch must contain either an updating expression or an empty sequence. Based on the value of the test expression, either the then or else clause is selected and evaluated. The result of the conditional updating expression is a list of updates returned by the selected branch. The containing transform expression performs the updates after merging them with updates returned by other updating expressions within the modify clause of the transform expression.
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.