条件表达式
条件表达式使用关键字 if、then 和 else 以根据测试表达式的值是 true 还是 false 来对两个表达式的其中一个求值。
语法
- 购买
- 直接放在测试表达式之前的关键字。
- 测试表达
- XQuery 表达式,用于确定条件表达式中要评估的部分。
- then
- 如果测试表达式的布尔值有效,则评估该关键字后面的表达式。 如果测试表达式的有效布尔值为 false,那么不会对表达式求值或检查是否有错。
- else
- 如果测试表达式的布尔值是假,则评估该关键字后面的表达式。 如果测试表达式的有效布尔值为 true,那么不会对表达式求值或检查是否有错。
- expression1 和 expression2
- 任何 XQuery 表达。 如果表达式包含顶级逗号运算符,那么必须用圆括号将表达式括起来。
限制 : test-expression、 expression1 和 expression2 不能包含FLWOR表达式。
示例
假设采购订单表中的订单列包含以下数据:
<ipo:purchaseOrder
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ipo="http://www.example.com/IPO"
orderDate="2008-12-01">
<shipTo exportCode="1" xsi:type="ipo:UKAddress">
<name>Helen Zoe</name>
<street>55 Eden Street</street>
<city>San Jose</city>
<state>CA</state>
<postcode>CB1 1JR</postcode>
</shipTo>
<shipTo exportCode="1" xsi:type="ipo:UKAddress">
<name>Joe Lee</name>
<street>66 University Avenue</street>
<city>Palo Alto</city>
<state>CA</state>
<postcode>CB1 1JR</postcode>
</shipTo>
<billTo xsi:type="ipo:USAddress">
<name>Robert Smith</name>
<street>8 Oak Avenue</street>
<city>Old Town</city>
<state>PA</state>
<zip>95819</zip>
</billTo>
<items>
<item partNum="833-AA">
<productName>Lapis necklace</productName>
<quantity>1</quantity>
<USPrice>99.95</USPrice>
<ipo:comment>Want this for the holidays!</ipo:comment>
<shipDate>2008-12-05</shipDate>
</item>
<item partNum="945-ZG">
<productName>Sapphire Bracelet</productName>
<quantity>2</quantity>
<USPrice>178.99</USPrice>
<shipDate>2009-01-03</shipDate>
</item>
</items>
</ipo:purchaseOrder>
在下面的示例中,查询构建了一个
item 元素的列表。 shipping 元素对于项目的价值是有条件的,取决于 USPrice 元素是否小于100。 在这个例子中,测试表达式根据 USPrice 元素的值构造一个xs:decimal值。 xs:decimal函数用于强制进行十进制比较。SELECT XMLQUERY(
'declare namespace ipo="http://www.example.com/IPO";
for $i in $po/ipo:purchaseOrder/items/item
return
<item>
{$i/productName}
<shipping>
{ if (xs:decimal($i/USPrice) lt 100) then 5 else 10 }
</shipping>
</item>'
PASSING PORDER as "po")
FROM PURCHASEORDER查询将返回以下结果:<item>
<productName
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ipo="http://www.example.com/IPO">
Lapis necklace
</productName>
<shipping>5</shipping>
</item>
<item>
<productName
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ipo="http://www.example.com/IPO">
Sapphire Bracelet
</productName>
<shipping>10</shipping>
</item>