XQuery

XQuery

(pwalmsley@datypic.com)

ISBN: 1491915103

2nd edition, , O'Reilly Media, Inc.

Chapter 8: Functions

Please note that the book contains many inline examples and informal tables that are not provided here.

Example 8-1. A function declaration
declare function local:discountPrice(
  $price as xs:decimal?,
  $discount as xs:decimal?,
  $maxDiscountPct as xs:integer?) as xs:decimal?

{
   let $maxDiscount := ($price * $maxDiscountPct) div 100
   let $actualDiscount := min( ($maxDiscount, $discount) )
   return ($price - $actualDiscount)
};

let $prod := doc("prices.xml")//prod[1]
return local:discountPrice($prod/price, $prod/discount, 15)
Example 8-2. Handling the empty sequence
declare function local:discountPrice(
  $price as xs:decimal?,
  $discount as xs:decimal?,
  $maxDiscountPct as xs:integer?) as xs:double?
{
   let $newDiscount    := if ($discount) then $discount else 0
   let $maxDiscount    := if ($maxDiscountPct)
                          then ($price * $maxDiscountPct) div 100
                          else 0
   let $actualDiscount := min( ($maxDiscount, $newDiscount) )
   return ($price - $actualDiscount)
};
let $prod := doc("prices.xml")//prod[1]
return local:discountPrice($prod/price, $prod/discount, 15)
Example 8-3. Invalid use of context in a function body
declare function local:prod2ndDigit() as xs:string? {
    substring(number, 2, 1)
};
doc("catalog.xml")//product[local:prod2ndDigit() > '5']
Example 8-4. Passing the context item to the function
declare function local:prod2ndDigit($prod as element()?) as xs:string? {
    substring($prod/number, 2, 1)
};
doc("catalog.xml")//product[local:prod2ndDigit(.) > '5']
Example 8-5. A recursive function
declare function local:num-descendant-elements
  ($el as element()) as xs:integer {
    sum(for $child in $el/*
        return local:num-descendant-elements($child) + 1)
};
Datypic XQuery Services