Skip to main content

XQuery Custom Functions

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.xqy
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))
90