SQL Functions
Advantages of UDFs
So why are UDFs important? What can you do with UDFs that you cannot with stored procedures? Well, UDFs are not functionally stronger than stored procedures (in fact, UDFs have many limitations, which we will examine shortly). However, UDFs do provide certain advantages, discussed in the following sections.SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. Do not confuse SQL functions with user-defined functions written in PL/SQL.
If you call a SQL function with an argument of a datatype other than the datatype expected by the SQL function, then Oracle attempts to convert the argument to the expected datatype before performing the SQL function. If you call a SQL function with a null argument, then the SQL function automatically returns null. The only SQL functions that do not necessarily follow this behavior are
CONCAT
, NVL
, and REPLACE
.In the syntax diagrams for SQL functions, arguments are indicated by their datatypes. When the parameter
function
appears in SQL syntax, replace it with one of the functions described in this section. Functions are grouped by the datatypes of their arguments and their return values. See Also:
|
function::=
Description of the illustration function.gif
single_row_function::=
Description of the illustration single_row_function.gif
The sections that follow list the built-in SQL functions in each of the groups illustrated in the preceding diagrams except user-defined functions. All of the built-in SQL functions are then described in alphabetical order.
See Also: "User-Defined Functions " and CREATE FUNCTION |
Single-Row Functions
Single-row functions return a single result row for every row of a queried table or view. These functions can appear in select lists,WHERE
clauses, START
WITH
and CONNECT
BY
clauses, and HAVING
clauses.Numeric Functions
Numeric functions accept numeric input and return numeric values. Most numeric functions that returnNUMBER
values that are accurate to 38 decimal digits. The transcendental functions COS
, COSH
, EXP
, LN
, LOG
, SIN
, SINH
, SQRT
, TAN
, and TANH
are accurate to 36 decimal digits. The transcendental functions ACOS
, ASIN
, ATAN
, and ATAN2
are accurate to 30 decimal digits. The numeric functions are:ABS
ACOS
ASIN
ATAN
ATAN2
BITAND
CEIL
COS
COSH
EXP
FLOOR
LN
LOG
MOD
NANVL
POWER
REMAINDER
ROUND (number)
SIGN
SIN
SINH
SQRT
TAN
TANH
TRUNC (number)
WIDTH_BUCKET
Character Functions Returning Character Values
Character functions that return character values return values of the same datatype as the input argument. The length of the value returned by the function is limited by the maximum length of the datatype returned.- For functions that return
CHAR
orVARCHAR2
, if the length of the return value exceeds the limit, then Oracle Database truncates it and returns the result without an error message. - For functions that return
CLOB
values, if the length of the return values exceeds the limit, then Oracle raises an error and returns no data.
CHR
CONCAT
INITCAP
LOWER
LPAD
LTRIM
NLS_INITCAP
NLS_LOWER
NLSSORT
NLS_UPPER
REGEXP_REPLACE
REGEXP_SUBSTR
REPLACE
RPAD
RTRIM
SOUNDEX
SUBSTR
TRANSLATE
TREAT
TRIM
UPPER
Character Functions Returning Number Values
Character functions that return number values can take as their argument any character datatype.The character functions that return number values are:
ASCII
INSTR
LENGTH
REGEXP_INSTR
Datetime Functions
Datetime functions operate on date (DATE
), timestamp (TIMESTAMP
, TIMESTAMP
WITH
TIME
ZONE
, and TIMESTAMP
WITH
LOCAL
TIME
ZONE
), and interval (INTERVAL
DAY
TO
SECOND
, INTERVAL
YEAR
TO
MONTH
) values.Some of the datetime functions were designed for the Oracle
DATE
datatype (ADD_MONTHS
, CURRENT_DATE
, LAST_DAY
, NEW_TIME
, and NEXT_DAY
). If you provide a timestamp value as their argument, Oracle Database internally converts the input type to a DATE
value and returns a DATE
value. The exceptions are the MONTHS_BETWEEN
function, which returns a number, and the ROUND
and TRUNC
functions, which do not accept timestamp or interval values at all.The remaining datetime functions were designed to accept any of the three types of data (date, timestamp, and interval) and to return a value of one of these types.
The datetime functions are:
ADD_MONTHS
CURRENT_DATE
CURRENT_TIMESTAMP
DBTIMEZONE
EXTRACT (datetime)
FROM_TZ
LAST_DAY
LOCALTIMESTAMP
MONTHS_BETWEEN
NEW_TIME
NEXT_DAY
NUMTODSINTERVAL
NUMTOYMINTERVAL
ROUND (date)
SESSIONTIMEZONE
SYS_EXTRACT_UTC
SYSDATE
SYSTIMESTAMP
TO_CHAR (datetime)
TO_TIMESTAMP
TO_TIMESTAMP_TZ
TO_DSINTERVAL
TO_YMINTERVAL
TRUNC (date)
TZ_OFFSET
Conversion Functions
Conversion functions convert a value from one datatype to another. Generally, the form of the function names follows the conventiondatatype
TO
datatype
. The first datatype is the input datatype. The second datatype is the output datatype. The SQL conversion functions are:ASCIISTR
BIN_TO_NUM
CAST
CHARTOROWID
COMPOSE
CONVERT
DECOMPOSE
HEXTORAW
NUMTODSINTERVAL
NUMTOYMINTERVAL
RAWTOHEX
RAWTONHEX
ROWIDTOCHAR
ROWIDTONCHAR
SCN_TO_TIMESTAMP
TIMESTAMP_TO_SCN
TO_BINARY_DOUBLE
TO_BINARY_FLOAT
TO_CHAR (character)
TO_CHAR (datetime)
TO_CHAR (number)
TO_CLOB
TO_DATE
TO_DSINTERVAL
TO_LOB
TO_MULTI_BYTE
TO_NCHAR (character)
TO_NCHAR (datetime)
TO_NCHAR (number)
TO_NCLOB
TO_NUMBER
TO_DSINTERVAL
TO_SINGLE_BYTE
TO_TIMESTAMP
TO_TIMESTAMP_TZ
TO_YMINTERVAL
TO_YMINTERVAL
TRANSLATE ... USING
UNISTR
Collection Functions
The collection functions operate on nested tables and varrays. The SQL collection functions are:CARDINALITY
COLLECT
POWERMULTISET
POWERMULTISET_BY_CARDINALITY
SET
Miscellaneous Single-Row Functions
The following single-row functions do not fall into any of the other single-row function categories:BFILENAME
COALESCE
CV
DECODE
DEPTH
DUMP
EMPTY_BLOB, EMPTY_CLOB
EXISTSNODE
EXTRACT (XML)
EXTRACTVALUE
GREATEST
LEAST
LNNVL
NLS_CHARSET_DECL_LEN
NLS_CHARSET_ID
NLS_CHARSET_NAME
NULLIF
NVL
NVL2
ORA_HASH
PATH
PRESENTNNV
PRESENTV
PREVIOUS
SYS_CONNECT_BY_PATH
SYS_CONTEXT
SYS_DBURIGEN
SYS_EXTRACT_UTC
SYS_GUID
SYS_TYPEID
SYS_XMLAGG
SYS_XMLGEN
UID
UPDATEXML
USER
USERENV
VSIZE
XMLAGG
XMLCOLATTVAL
XMLCONCAT
XMLFOREST
XMLSEQUENCE
XMLTRANSFORM
Aggregate Functions
Aggregate functions return a single result row based on groups of rows, rather than on single rows. Aggregate functions can appear in select lists and inORDER
BY
and HAVING
clauses. They are commonly used with the GROUP
BY
clause in a SELECT
statement, where Oracle Database divides the rows of a queried table or view into groups. In a query containing a GROUP
BY
clause, the elements of the select list can be aggregate functions, GROUP
BY
expressions, constants, or expressions involving one of these. Oracle applies the aggregate functions to each group of rows and returns a single result row for each group.If you omit the
GROUP
BY
clause, then Oracle applies aggregate functions in the select list to all the rows in the queried table or view. You use aggregate functions in the HAVING
clause to eliminate groups from the output based on the results of the aggregate functions, rather than on the values of the individual rows of the queried table or view. See Also: "Using the GROUP BY Clause: Examples" and the "HAVING Clause " for more information on the GROUP BY clause and HAVING clauses in queries and subqueries |
-
DISTINCT
causes an aggregate function to consider only distinct values of the argument expression. -
ALL
causes an aggregate function to consider all values, including all duplicates.
DISTINCT
average of 1, 1, 1, and 3 is 2. The ALL
average is 1.5. If you specify neither, then the default is ALL
.All aggregate functions except
COUNT
(*) and GROUPING
ignore nulls. You can use the NVL
function in the argument to an aggregate function to substitute a value for a null. COUNT
never returns null, but returns either a number or zero. For all the remaining aggregate functions, if the data set contains no rows, or contains only rows with nulls as arguments to the aggregate function, then the function returns null.You can nest aggregate functions. For example, the following example calculates the average of the maximum salaries of all the departments in the sample schema
hr
:SELECT AVG(MAX(salary)) FROM employees GROUP BY department_id; AVG(MAX(SALARY)) ---------------- 10925This calculation evaluates the inner aggregate (
MAX
(salary
)) for each group defined by the GROUP
BY
clause (department_id
), and aggregates the results again.The aggregate functions are:
AVG
COLLECT
CORR
CORR_*
COUNT
COVAR_POP
COVAR_SAMP
CUME_DIST
DENSE_RANK
FIRST
GROUP_ID
GROUPING
GROUPING_ID
LAST
MAX
MEDIAN
MIN
PERCENTILE_CONT
PERCENTILE_DISC
PERCENT_RANK
RANK
REGR_ (Linear Regression) Functions
STATS_BINOMIAL_TEST
STATS_CROSSTAB
STATS_F_TEST
STATS_KS_TEST
STATS_MODE
STATS_MW_TEST
STATS_ONE_WAY_ANOVA
STATS_T_TEST_*
STATS_WSR_TEST
STDDEV
STDDEV_POP
STDDEV_SAMP
SUM
VAR_POP
VAR_SAMP
VARIANCE
Analytic Functions
Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. The group of rows is called a window and is defined by theanalytic_clause
. For each row, a sliding window of rows is defined. The window determines the range of rows used to perform the calculations for the current row. Window sizes can be based on either a physical number of rows or a logical interval such as time.Analytic functions are the last set of operations performed in a query except for the final
ORDER
BY
clause. All joins and all WHERE
, GROUP
BY
, and HAVING
clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER
BY
clause.Analytic functions are commonly used to compute cumulative, moving, centered, and reporting aggregates.
analytic_function::=
Description of the illustration analytic_function.gif
analytic_clause::=
Description of the illustration analytic_clause.gif
query_partition_clause::=
Description of the illustration query_partition_clause.gif
order_by_clause::=
Description of the illustration order_by_clause.gif
windowing_clause ::=
Description of the illustration windowing_clause.gif
The semantics of this syntax are discussed in the sections that follow.
analytic_function
Specify the name of an analytic function (see the listing of analytic functions following this discussion of semantics).
arguments
Analytic functions take 0 to 3 arguments. The arguments can be any numeric datatype or any nonnumeric datatype that can be implicitly converted to a numeric datatype. Oracle determines the argument with the highest numeric precedence and implicitly converts the remaining arguments to that datatype. The return type is also that datatype, unless otherwise noted for an individual function.
See Also: "Numeric Precedence " for information on numeric precedence and Table 2-11, "Implicit Type Conversion Matrix" for more information on implicit conversion |
analytic_clause
Use
OVER
analytic_clause
to indicate that the function operates on a query result set. That is, it is computed after the FROM
, WHERE
, GROUP
BY
, and HAVING
clauses. You can specify analytic functions with this clause in the select list or ORDER
BY
clause. To filter the results of a query based on an analytic function, nest these functions within the parent query, and then filter the results of the nested subquery.- Notes on the analytic_clause:
-
- You cannot specify any analytic function in any part of the
analytic_clause
. That is, you cannot nest analytic functions. However, you can specify an analytic function in a subquery and compute another analytic function over it. - You can specify
OVER
analytic_clause
with user-defined analytic functions as well as built-in analytic functions. See CREATE FUNCTION .
- You cannot specify any analytic function in any part of the
query_partition_clause
Use the
PARTITION
BY
clause to partition the query result set into groups based on one or more value_expr
. If you omit this clause, then the function treats all rows of the query result set as a single group.To use the
query_partition_clause
in an analytic function, use the upper branch of the syntax (without parentheses). To use this clause in a model query (in the model_column_clauses
) or a partitioned outer join (in the outer_join_clause
), use the lower branch of the syntax (with parentheses).You can specify multiple analytic functions in the same query, each with the same or different
PARTITION
BY
keys.If the objects being queried have the parallel attribute, and if you specify an analytic function with the
query_partition_clause
, then the function computations are parallelized as well.Valid values of
value_expr
are constants, columns, nonanalytic functions, function expressions, or expressions involving any of these.order_by_clause
Use the
order_by_clause
to specify how data is ordered within a partition. For all analytic functions except PERCENTILE_CONT
and PERCENTILE_DISC
(which take only a single key), you can order the values in a partition on multiple keys, each defined by a value_expr
and each qualified by an ordering sequence.Within each function, you can specify multiple ordering expressions. Doing so is especially useful when using functions that rank values, because the second expression can resolve ties between identical values for the first expression.
Whenever the
order_by_clause
results in identical values for multiple rows, the function returns the same result for each of those rows. Please refer to the analytic example for SUM for an illustration of this behavior.Restriction on the ORDER BY Clause
When used in an analytic function, the
order_by_clause
must take an expression (expr
). The SIBLINGS
keyword is not valid (it is relevant only in hierarchical queries). Position (position
) and column aliases (c_alias
) are also invalid. Otherwise this order_by_clause
is the same as that used to order the overall query or subquery.ASC | DESC
Specify the ordering sequence (ascending or descending).
ASC
is the default.NULLS FIRST | NULLS LAST
Specify whether returned rows containing nulls should appear first or last in the ordering sequence.
NULLS
LAST
is the default for ascending order, and NULLS
FIRST
is the default for descending order.Analytic functions always operate on rows in the order specified in the
order_by_clause
of the function. However, the order_by_clause
of the function does not guarantee the order of the result. Use the order_by_clause
of the query to guarantee the final result ordering. See Also: order_by_clause of SELECT for more information on this clause |
windowing_clause
Some analytic functions allow the
windowing_clause
. In the listing of analytic functions at the end of this section, the functions that allow the windowing_clause
are followed by an asterisk (*).ROWS | RANGE
These keywords define for each row a window (a physical or logical set of rows) used for calculating the function result. The function is then applied to all the rows in the window. The window moves through the query result set or partition from top to bottom.
-
ROWS
specifies the window in physical units (rows). -
RANGE
specifies the window as a logical offset.
order_by_clause
.The value returned by an analytic function with a logical offset is always deterministic. However, the value returned by an analytic function with a physical offset may produce nondeterministic results unless the ordering expression results in a unique ordering. You may have to specify multiple columns in the
order_by_clause
to achieve this unique ordering.BETWEEN ... AND
Use the
BETWEEN
... AND
clause to specify a start point and end point for the window. The first expression (before AND
) defines the start point and the second expression (after AND
) defines the end point.If you omit
BETWEEN
and specify only one end point, then Oracle considers it the start point, and the end point defaults to the current row.UNBOUNDED PRECEDING
Specify
UNBOUNDED
PRECEDING
to indicate that the window starts at the first row of the partition. This is the start point specification and cannot be used as an end point specification.UNBOUNDED FOLLOWING
Specify
UNBOUNDED
FOLLOWING
to indicate that the window ends at the last row of the partition. This is the end point specification and cannot be used as a start point specification.CURRENT ROW
As a start point,
CURRENT
ROW
specifies that the window begins at the current row or value (depending on whether you have specified ROW
or RANGE
, respectively). In this case the end point cannot be value_expr
PRECEDING
.As an end point,
CURRENT
ROW
specifies that the window ends at the current row or value (depending on whether you have specified ROW
or RANGE
, respectively). In this case the start point cannot be value_expr
FOLLOWING
.value_expr PRECEDING or value_expr FOLLOWING
For
RANGE
or ROW
:- If
value_expr
FOLLOWING
is the start point, then the end point must bevalue_expr
FOLLOWING
. - If
value_expr
PRECEDING
is the end point, then the start point must bevalue_expr
PRECEDING
.
See Also: NUMTOYMINTERVAL and NUMTODSINTERVAL for information on converting numeric times into intervals |
ROWS
:-
value_expr
is a physical offset. It must be a constant or expression and must evaluate to a positive numeric value. - If
value_expr
is part of the start point, then it must evaluate to a row before the end point.
RANGE
:-
value_expr
is a logical offset. It must be a constant or expression that evaluates to a positive numeric value or an interval literal. Please refer to "Literals " for information on interval literals. - You can specify only one expression in the
order_by_clause
- If
value_expr
evaluates to a numeric value, then theORDER
BY
expr
must be a numeric orDATE
datatype. - If
value_expr
evaluates to an interval value, then theORDER
BY
expr
must be aDATE
datatype.
windowing_clause
entirely, then the default is RANGE
BETWEEN
UNBOUNDED
PRECEDING
AND
CURRENT
ROW
.Analytic functions are commonly used in data warehousing environments. In the list of analytic functions that follows, functions followed by an asterisk (*) allow the full syntax, including the
windowing_clause
.AVG *
CORR *
COVAR_POP *
COVAR_SAMP *
COUNT *
CUME_DIST
DENSE_RANK
FIRST
FIRST_VALUE *
LAG
LAST
LAST_VALUE *
LEAD
MAX *
MIN *
NTILE
PERCENT_RANK
PERCENTILE_CONT
PERCENTILE_DISC
RANK
RATIO_TO_REPORT
REGR_ (Linear Regression) Functions *
ROW_NUMBER
STDDEV *
STDDEV_POP *
STDDEV_SAMP *
SUM *
VAR_POP *
VAR_SAMP *
VARIANCE *
See Also: Oracle Data Warehousing Guide for more information on these functions and for scenarios illustrating their use |
Object Reference Functions
Object reference functions manipulate REFs, which are references to objects of specified object types. The object reference functions are:DEREF
MAKE_REF
REF
REFTOHEX
VALUE
See Also: Oracle Database Concepts for more information about REFs |
Model Functions
Model functions are relevant only for interrow calculations and can be used only in themodel_clause
of the SELECT
statement. They are nonrecursive. The model functions are:CV
ITERATION_NUMBER
PRESENTNNV
PRESENTV
PREVIOUS
...............................................................................................................................................................................................
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.Useful aggregate functions:
- AVG() - Returns the average value
- COUNT() - Returns the number of rows
- FIRST() - Returns the first value
- LAST() - Returns the last value
- MAX() - Returns the largest value
- MIN() - Returns the smallest value
- SUM() - Returns the sum
SQL Scalar functions
SQL scalar functions return a single value, based on the input value.Useful scalar functions:
- UCASE() - Converts a field to upper case
- LCASE() - Converts a field to lower case
- MID() - Extract characters from a text field
- LEN() - Returns the length of a text field
- ROUND() - Rounds a numeric field to the number of decimals specified
- NOW() - Returns the current system date and time
- FORMAT() - Formats how a field is to be displayed
......................................................................................................................................................................
CREATE FUNCTION (SQL Scalar, Table, or Row) statement
The CREATE FUNCTION (SQL Scalar, Table, or Row) statement is used to define a user-defined SQL scalar, table, or row function. A scalar function returns a single value each time it is invoked, and is generally valid wherever an SQL expression is valid. A table function can be used in a FROM clause and returns a table. A row function can be used as a transform function and returns a row.
Invocation This statement can be embedded in an application program or issued through the use of dynamic SQL statements. It is an executable statement that can be dynamically prepared only if DYNAMICRULES run behavior is in effect for the package (SQLSTATE 42509).
Authorization The privileges held by the authorization ID of the statement must include at least one of the following:
Authorization requirements of the data source for the table or view referenced by the nickname are applied when the function is invoked. The authorization ID of the connection can be mapped to a different remote authorization ID.
If a function definer can only create the function because the definer has SYSADM authority, the definer is granted implicit DBADM authority for the purpose of creating the function.
If the authorization ID of the statement does not have SYSADM or DBADM authority, the privileges held by the authorization ID of the statement must also include all of the privileges necessary to invoke the SQL statements that are specified in the function body.
- For each table, view, or nickname identified in any fullselect:
- CONTROL privilege on that table, view, or nickname, or
- SELECT privilege on that table, view, or nickname
- IMPLICIT_SCHEMA authority on the database, if the implicit or explicit schema name of the function does not exist
- CREATEIN privilege on the schema, if the schema name of the function refers to an existing schema
- SYSADM or DBADM authority
Authorization requirements of the data source for the table or view referenced by the nickname are applied when the function is invoked. The authorization ID of the connection can be mapped to a different remote authorization ID.
If a function definer can only create the function because the definer has SYSADM authority, the definer is granted implicit DBADM authority for the purpose of creating the function.
If the authorization ID of the statement does not have SYSADM or DBADM authority, the privileges held by the authorization ID of the statement must also include all of the privileges necessary to invoke the SQL statements that are specified in the function body.
Syntax
>>-CREATE FUNCTION--function-name-------------------------------> >--(--+--------------------------------+--)--*------------------> | .-,--------------------------. | | V | | '---parameter-name--data-type1-+-' >--RETURNS--+-data-type2-----------------+--*-------------------> '-+-ROW---+--| column-list |-' '-TABLE-' .-LANGUAGE SQL-. >--+-------------------------+--*--+--------------+--3 *----------> '-SPECIFIC--specific-name-' .-NOT DETERMINISTIC-. >--+------------------------------+--*--+-------------------+---> '-3 PARAMETER CCSID--+-3 ASCII---+-' '-DETERMINISTIC-----' '-3 UNICODE-' .-EXTERNAL ACTION----. .-READS SQL DATA---------. >--*--+--------------------+--*--+------------------------+-----> '-NO EXTERNAL ACTION-' +-CONTAINS SQL-----------+ | (1) | '-4 MODIFIES SQL DATA------' .-STATIC DISPATCH-. .-CALLED ON NULL INPUT-. >--*--+-----------------+--*--+----------------------+--*-------> .-INHERIT SPECIAL REGISTERS-. >--+---------------------------+--*-----------------------------> >--+----------------------------------------------------+-------> | (2) | '-PREDICATES--(--| predicate-specification |--)------' .-7 INHERIT ISOLATION LEVEL WITHOUT LOCK REQUEST-. >--+----------------------------------------------+-------------> '-7 INHERIT ISOLATION LEVEL WITH LOCK REQUEST----' >--| SQL-function-body |--------------------------------------->< column-list: .-,-----------------------. V | |--(----column-name--data-type3-+--)----------------------------| SQL-function-body: |--+-RETURN Statement-----------+-------------------------------| '-dynamic-compound-statement-'
Notes:
- 4 Valid only if RETURNS specifies a table (TABLE column-list)
- Valid only if RETURNS specifies a scalar result (data-type2)
Description
- function-name
- Names the function being defined. It is a qualified or unqualified name that designates a function. The unqualified form of function-name is an SQL identifier (with a maximum length of 18). In dynamic SQL statements, the CURRENT SCHEMA special register is used as a qualifier for an unqualified object name. In static SQL statements the QUALIFIER precompile/bind option implicitly specifies the qualifier for unqualified object names. The qualified form is a schema-name followed by a period and an SQL identifier. The name, including the implicit or explicit qualifiers, together with the number of parameters and the data type of each parameter (without regard for any length, precision or scale attributes of the data type) must not identify a function described in the catalog (SQLSTATE 42723). The unqualified name, together with the number and data types of the parameters, while of course unique within its schema, need not be unique across schemas. If a two-part name is specified, the schema-name cannot begin with 'SYS' (SQLSTATE 42939). A number of names used as keywords in predicates are reserved for system use, and cannot be used as a function-name (SQLSTATE 42939). The names are SOME, ANY, ALL, NOT, AND, OR, BETWEEN, NULL, LIKE, EXISTS, IN, UNIQUE, OVERLAPS, SIMILAR, MATCH, and the comparison operators. The same name can be used for more than one function if there is some difference in the signature of the functions. Although there is no prohibition against it, an external user-defined table function should not be given the same name as a built-in function.
- parameter-name
- A name that is distinct from the names of all other parameters in this function.
- data-type1
- Specifies the data type of the parameter:
- SQL data type specifications and abbreviations that may be specified in the data-type1 definition of a CREATE TABLE statement.
- REF may be specified, but that REF is unscoped. The system does not attempt to infer the scope of the parameter or result. Inside the body of the function, a reference type can be used in a dereference operation only by first casting it to have a scope. Similarly, a reference returned by an SQL function can be used in a dereference operation only by first casting it to have a scope.
- LONG VARCHAR and LONG VARGRAPHIC data types may not be used (SQLSTATE 42815).
- RETURNS
- This mandatory clause identifies the type of output of the function.
- data-type2
- Specifies the data type of the output. In this statement, exactly the same considerations apply as for the parameters of SQL functions described above under data-type1 for function parameters.
- ROW column-list
- Specifies that the output of the function is a single row. If the function returns more than one row, an error is raised (SQLSTATE 21505). The column-list must include at least two columns (SQLSTATE 428F0). A row function can only be used as a transform function for a structured type (having one structured type as its parameter and returning only base types).
- TABLE column-list
- Specifies that the output of the function is a table.
- column-list
- The list of column names and data types returned for a ROW or TABLE function
- column-name
- Specifies the name of this column. The name cannot be qualified and the same name cannot be used for more than one column of the row.
- data-type3
- Specifies the data type of the column, and can be any data type supported by a parameter of the SQL function.
- SPECIFIC specific-name
- Provides a unique name for the instance of the function that is being defined. This specific name can be used when sourcing on this function, dropping the function, or commenting on the function. It can never be used to invoke the function. The unqualified form of specific-name is an SQL identifier (with a maximum length of 18). The qualified form is a schema-name followed by a period and an SQL identifier. The name, including the implicit or explicit qualifier, must not identify another function instance that exists at the application server; otherwise an error is raised (SQLSTATE 42710). The specific-name may be the same as an existing function-name.
If no qualifier is specified, the qualifier that was used for function-name is used. If a qualifier is specified, it must be the same as the explicit or implicit qualifier of function-name or an error is raised (SQLSTATE 42882).
If specific-name is not specified, a unique name is generated by the database manager. The unique name is SQL followed by a character timestamp, SQLyymmddhhmmssxxx.
- LANGUAGE SQL
- Specifies that the function is written using SQL. 3 3
- PARAMETER CCSID
- Specifies the encoding scheme to use for all string data 3 passed into and out of the function. 3 If the PARAMETER CCSID clause is not specified, the default is 3 PARAMETER CCSID UNICODE for Unicode databases, and PARAMETER CCSID 3 ASCII for all other databases. 3 3
- 3
- ASCII 3
- Specifies that string data is encoded in the database 3 code page. 3 If the database is a Unicode database, PARAMETER CCSID ASCII cannot 3 be specified (SQLSTATE 56031). 3 3
- UNICODE 3
- Specifies that character data is in UTF-8, and that graphic 3 data is in UCS-2. 3 If the database is not a Unicode database, PARAMETER CCSID UNICODE 3 cannot be specified (SQLSTATE 56031). 3 3
- DETERMINISTIC or NOT DETERMINISTIC
- This optional clause specifies whether the function always returns the same results for given argument values (DETERMINISTIC) or whether the function depends on some state values that affect the results (NOT DETERMINISTIC). That is, a DETERMINISTIC function must always return the same table from successive invocations with identical inputs. Optimizations taking advantage of the fact that identical inputs always produce the same results are prevented by specifying NOT DETERMINISTIC. NOT DETERMINISTIC must be explicitly or implicitly specified if the body of the function accesses a special register or calls another non-deterministic function (SQLSTATE 428C2).
- NO EXTERNAL ACTION or EXTERNAL ACTION
- This optional clause specifies whether or not the function takes some action that changes the state of an object not managed by the database manager. By specifying NO EXTERNAL ACTION, the system can use certain optimizations that assume functions have no external impacts. EXTERNAL ACTION must be explicitly or implicitly specified if the body of the function calls another function that has an external action (SQLSTATE 428C2).
4 4 - CONTAINS SQL, READS SQL DATA, or MODIFIES SQL DATA
- Indicates what type of SQL statements can be executed. 4 4
- 4
- CONTAINS SQL 4
- Indicates that SQL statements that neither read nor modify SQL data 4 can be executed by the function (SQLSTATE 42985). 4 4
- READS SQL DATA 4
- Indicates that SQL statements that do not modify SQL 4 data can be executed by the function (SQLSTATE 42985). 4 4 4
- MODIFIES SQL DATA 4
- Indicates that all SQL statements supported in 4 dynamic-compound-statement can be executed by the function. 4 4 4
- STATIC DISPATCH
- This optional clause indicates that at function resolution time, DB2 chooses a function based on the static types (declared types) of the parameters of the function.
- CALLED ON NULL INPUT
- This clause indicates that the function is called regardless of whether any of its arguments are null. It can return a null value or a non-null value. Responsibility for testing null argument values lies with the user-defined function. The phrase NULL CALL may be used in place of CALLED ON NULL INPUT.
- INHERIT SPECIAL REGISTERS
- This optional clause indicates that updatable special registers in the function will inherit their initial values from the environment of the invoking statement. For a function that is invoked in the select-statement of a cursor, the initial values are inherited from the environment when the cursor is opened. For a routine that is invoked in a nested object (for example, a trigger or a view), the initial values are inherited from the runtime environment (not the object definition). No changes to the special registers are passed back to the caller of the function.
Some special registers, such as the datetime special registers, reflect a property of the statement currently executing, and are therefore never inherited from the caller.
- PREDICATES
- For predicates using this function, this clause identifies those that can exploit the index extensions, and can use the optional SELECTIVITY clause for the predicate's search condition. If the PREDICATES clause is specified, the function must be defined as DETERMINISTIC with NO EXTERNAL ACTION (SQLSTATE 42613). 3 If the PREDICATES clause is specified, and the database 3 is not a Unicode database, PARAMETER CCSID UNICODE must not be 3 specified (SQLSTATE 42613).
- predicate-specification
- For details on predicate specification, see "CREATE FUNCTION (External Scalar)".
7 7 - INHERIT ISOLATION LEVEL WITHOUT LOCK REQUEST or INHERIT ISOLATION LEVEL WITH LOCK REQUEST
- Specifies whether or not a lock request can be associated with 7 the isolation-clause of the statement when the function inherits the 7 isolation level of the statement that invokes the function. 7 The default is INHERIT ISOLATION LEVEL WITHOUT LOCK REQUEST. 7 7
- 7
- INHERIT ISOLATION LEVEL WITHOUT LOCK REQUEST 7
- Specifies that, as the function inherits the isolation level of 7 the invoking statement, it cannot be invoked in the context of an SQL 7 statement which includes a lock-request-clause as part of a specified 7 isolation-clause (SQLSTATE 42601). 7 7
- INHERIT ISOLATION LEVEL WITH LOCK REQUEST 7
- Specifies that, as the function inherits the isolation level of 7 the invoking statement, it also inherits the specified 7 lock-request-clause. 7 7
- SQL-function-body
- Specifies the body of the function. Parameter names can be referenced in the SQL-function-body. Parameter names may be qualified with the function name to avoid ambiguous references. If the SQL-function-body is a dynamic compound statement, it must contain at least one RETURN statement, and a RETURN statement must be executed when the function is called (SQLSTATE 42632). If the function is a table or row function, it can contain only one RETURN statement, which must be the last statement in the dynamic compound statement (SQLSTATE 429BD).
3
4
7
Notes
- Resolution of function calls inside the function body is done according to the function path that is effective for the CREATE FUNCTION statement and does not change after the function is created.
- If an SQL function contains multiple references to any of the date or time special registers, all references return the same value, and it will be the same value returned by the register invocation in the statement that called the function.
- The body of an SQL function cannot contain a recursive call to itself or to another function or method that calls it, since such a function could not exist to be called.
- The following rules are enforced by all statements that create functions or methods:
- A function may not have the same signature as a method (comparing the first parameter-type of the function with the subject-type of the method).
- A function and a method may not be in an overriding relationship. That is, if the function were a method with its first parameter as subject, it must not override, or be overridden by, another method. For more information about overriding methods, see the "CREATE TYPE (Structured)" statement.
- Because overriding does not apply to functions, it is permissible for two functions to exist such that, if they were methods, one would override the other.
- Parameter-names, lengths, AS LOCATOR, and FOR BIT DATA are ignored.
- A subtype is considered to be different from its supertype.
- Table access restrictions If a function is defined as READS SQL DATA, no statement in the function can access a table that is being modified by the statement that invoked the function (SQLSTATE 57053). For example, suppose the user-defined function BONUS() is defined as READS SQL DATA. If the statement UPDATE EMPLOYEE SET SALARY = SALARY + BONUS(EMPNO) is invoked, no SQL statement in the BONUS function can read from the EMPLOYEE table.
7 If a function defined with MODIFIES SQL DATA contains 7 nested CALL statements, read access to the tables being modified by 7 the function (by either the function definition or the statement that 7 invoked the function) is not allowed (SQLSTATE 57053).
- Privileges The definer of a function always receives the EXECUTE privilege on the function, as well as the right to drop the function. The definer of a function is also given the WITH GRANT OPTION on the function if the definer has WITH GRANT OPTION on all privileges required to define the function, or if the definer has SYSADM or DBADM authority.
The definer of a function only acquires privileges if the privileges from which they are derived exist at the time the function is created. The definer must have these privileges either directly, or because PUBLIC has the privileges. Privileges held by groups of which the function definer is a member are not considered. When using the function, the connected user's authorization ID must have the valid privileges on the table or view that the nickname references at the data source.
- Compatibilities
- 3 For compatibility with DB2 UDB for OS/390 and z/OS: 3 3
- 3
- The following syntax is accepted as the default behavior: 3 3
- 3
- CCSID UNICODE in a Unicode database 3
- CCSID ASCII in a non-Unicode database
- The following syntax is accepted as the default behavior: 3 3
- For compatibility with previous versions of DB2:
- NULL CALL can be specified in place of CALLED ON NULL INPUT
- 3 For compatibility with DB2 UDB for OS/390 and z/OS: 3 3
Examples Example 1: Define a scalar function that returns the tangent of a value using the existing sine and cosine functions.
4
CREATE FUNCTION TAN (X DOUBLE) RETURNS DOUBLE LANGUAGE SQL CONTAINS SQL NO EXTERNAL ACTION DETERMINISTIC RETURN SIN(X)/COS(X)Example 2: Define a transform function for the structured type PERSON.
CREATE FUNCTION FROMPERSON (P PERSON) RETURNS ROW (NAME VARCHAR(10), FIRSTNAME VARCHAR(10)) LANGUAGE SQL CONTAINS SQL NO EXTERNAL ACTION DETERMINISTIC RETURN VALUES (P..NAME, P..FIRSTNAME)Example 3: Define a table function that returns the employees in a specified department number.
CREATE FUNCTION DEPTEMPLOYEES (DEPTNO CHAR(3)) RETURNS TABLE (EMPNO CHAR(6), LASTNAME VARCHAR(15), FIRSTNAME VARCHAR(12)) LANGUAGE SQL READS SQL DATA NO EXTERNAL ACTION DETERMINISTIC RETURN SELECT EMPNO, LASTNAME, FIRSTNME FROM EMPLOYEE WHERE EMPLOYEE.WORKDEPT = DEPTEMPLOYEES.DEPTNOExample 4: Define a scalar function that reverses a string.
CREATE FUNCTION REVERSE(INSTR VARCHAR(4000)) RETURNS VARCHAR(4000) DETERMINISTIC NO EXTERNAL ACTION CONTAINS SQL BEGIN ATOMIC DECLARE REVSTR, RESTSTR VARCHAR(4000) DEFAULT ''; DECLARE LEN INT; IF INSTR IS NULL THEN RETURN NULL; END IF; SET (RESTSTR, LEN) = (INSTR, LENGTH(INSTR)); WHILE LEN > 0 DO SET (REVSTR, RESTSTR, LEN) = (SUBSTR(RESTSTR, 1, 1) CONCAT REVSTR, SUBSTR(RESTSTR, 2, LEN - 1), LEN - 1); END WHILE; RETURN REVSTR; END4 Example 4: 4 Define the table function from Example 4 with auditing. 4
4
CREATE FUNCTION DEPTEMPLOYEES (DEPTNO CHAR(3)) 4 RETURNS TABLE (EMPNO CHAR(6), 4 LASTNAME VARCHAR(15), 4 FIRSTNAME VARCHAR(12)) 4 LANGUAGE SQL 4 MODIFIES SQL DATA 4 NO EXTERNAL ACTION 4 DETERMINISTIC 4 BEGIN ATOMIC 4 INSERT INTO AUDIT 4 VALUES (USER, 4 'Table: EMPLOYEE Prd: DEPTNO = ' CONCAT DEPTNO); 4 RETURN 4 SELECT EMPNO, LASTNAME, FIRSTNME 4 FROM EMPLOYEE 4 WHERE EMPLOYEE.WORKDEPT = DEPTEMPLOYEES.DEPTNO 4 END
.........................................................................................................................................................................................................................
0 comments:
Post a Comment