Home > XQuery Resources > XQuery Tutorial> User-Defined Functions
User defined functions provide a way for XQuery users to create re-usable expressions in their queries. Below, we demonstrate the creation of user-defined functions through some examples:

 
{-- Basic function that takes an decimal type value as
    argument and returns it incremented by 1 --}

define function increment($num as xs:decimal) as xs:decimal {
    $num + 1
}

increment(10.4)





{-- define a function in a namespace and use a function call
    with a qualified name --}

declare namespace math = "http://www.example.com/math"

define function math:square($num as xs:decimal) as xs:decimal {
    $num * $num
}

math:square(5.3)





{-- Recursive function for calculating the factorial of an
    integer --}

define function fac ($n as xs:integer) as xs:integer {
if ($n = 0)
then 1
else $n * fac($n - 1)
}

<factorial>{fac(10)}</factorial>





{-- For each bid in the document R-bids.xml, get the
    description and reserve_price using the user-defined
    function getItemDetails --}

{-- User defined function that takes a bid_tuple element
    and the item repository (R-items.xml) as parameters
    and returns the details of the item being bidded --}

define function getItemDetails($bidTuple as node, $itemRepository as node)
  as node {
  for $i in $itemRepository/items/item_tuple
  where $i/itemno = $bidTuple/itemno
  return
    <item>
        {$bidTuple/bid}
        {$i/description}
        {$i/reserve_price}
    </item>
}

<BidInformation>
{
  let $item_rep := document("data/R-items.xml")
  for $bid in document("data/R-bids.xml")/bids/bid_tuple
  return
    <BidItemDetails>
      <each_item>
        {getItemDetails($bid, $item_rep)}
      </each_item>
    </BidItemDetails>
}
</BidInformation>

 


Company | Products | Solutions | News & Events | Developers | Contact Us | Site Map