Xquery Functions
# XQuery Functions
* * *
XQuery 1.0, XPath 2.0, and XSLT 2.0 share the same function library.
* * *
## XQuery Functions
XQuery contains over 100 built-in functions. These functions are used for string values, numeric, date and time comparisons, node and QName operations, sequence operations, logical values, and more. You can also define your own functions in XQuery.
* * *
## XQuery Built-in Functions
The URI for the XQuery function namespace is:
http://www.w3.org/2005/02/xpath-functions
The default prefix for the function namespace is `fn:`.
Tip: Functions are often called using the `fn:` prefix, for example `fn:string()`. However, since `fn:` is the default prefix for the namespace, the prefix does not need to be used when calling the function.
You can find the complete (#) in our XPath tutorial.
* * *
## Function Call Examples
Function calls can be used with expressions. Look at the examples below:
### Example 1: Inside an Element
{upper-case($booktitle)}
### Example 2: In a Predicate of a Path Expression
doc("books.xml")/bookstore/book[substring(title,1,5)='Harry']
### Example 3: In a let Statement
let $name := (substring($booktitle,1,4))
* * *
## XQuery User-Defined Functions
If you cannot find the XQuery function you need, you can write your own functions.
User-defined functions can be defined in the query or in a separate library.
### Syntax
declare function _prefix:function-name_($_parameter_ AS _data-type_)
AS _return-data-type_
{
..._function code_...
}
### Notes on User-Defined Functions:
* Use the `declare function` keyword.
* The function name must use a prefix.
* The data type of the parameters is usually consistent with the data types defined in the XML Schema.
* The function body must be enclosed in curly braces `{}`.
### An Example of a User-Defined Function Declared in a Query:
declare function local:minPrice($p as xs:decimal?,$d as xs:decimal?)
AS xs:decimal?
{
let $disc := ($p * $d) div 100
return ($p - $disc)
}
Below is an example of how to call the function above:
{local:minPrice($book/price,$book/discount)}
YouTip