Skip to content

XQuery Custom Functions

How to create XQuery custom functions using declare function syntax, proper data typing, and XML namespace prefixes for reusable logic.

XQuery Custom Functions

XQuery provides the ability to write custom functions. The following are guidelines for creating a custom function.

  • Use the declare function keyword to define a function.
  • Use the data types defined in the current XML schema.
  • Enclose the body of function inside curly braces.
  • Prefixes the function name with an XML namespace.

Syntax

declare function prefix:function_name($parameter as datatype?...)
as returnDatatype?
{
   function body...
};

Example

The following example shows how to create a user-defined function in XQuery.

example.xqyxquery
declare function local:discount($price as xs:decimal?,$percentDiscount as xs:decimal?)
as xs:decimal? {
   let $discount := $price - ($price * $percentDiscount div 100)
   return $discount
};

let $originalPrice := 100

let $discountValue := 10

return (local:discount($originalPrice, $discountValue)) 
Outputplaintext
90
Navigation