CREATE FUNCTION Statement

Creates a new function in the database.

Syntax

Syntax 1
CREATE [ OR REPLACE ] [ TEMPORARY ] FUNCTIONowner.]function-name  ( [ parameter, … ] )
 RETURNS data-type routine-characteristics
 SQL SECURITYINVOKER | DEFINER } ]
 { compound-statement
  AS tsql-compound-statementexternal-name }
Syntax 2
CREATE FUNCTIONowner.]function-name ( [ parameter, … ] )
 RETURNS data-type
 URL url-stringHEADER header-string ]
 [ SOAPHEADER soap-header-string ]
 [ TYPE { 'HTTP[:{ GET | POST } ] ' | 'SOAP[:{ RPC | DOC } ]' } ]
 [ NAMESPACE namespace-string ]
 [ CERTIFICATE certificate-string ]
 [ CLIENTPORT clientport-string ]
 [ PROXY proxy-string ]

Parameters

Examples

Usage

The CREATE FUNCTION statement creates a user-defined function in the database. A function can be created for another user by specifying an owner name. Subject to permissions, a user-defined function can be used in exactly the same way as other non-aggregate functions.

Functions that have side effects, such as modifying the underlying data, should be declared as NOT DETERMINISTIC. For example, a function that generates primary key values and is used in an INSERT … SELECT statement should be declared NOT DETERMINISTIC:

CREATE FUNCTION keygen( increment INTEGER ) 
RETURNS INTEGER 
NOT DETERMINISTIC 
BEGIN   
  DECLARE keyval INTEGER;  
  UPDATE counter SET x = x + increment;  
  SELECT counter.x INTO keyval FROM counter;   
  RETURN keyval 
END 
INSERT INTO new_table 
SELECT keygen(1), ... 
FROM old_table

Functions may be declared as DETERMINISTIC if they always return the same value for given input parameters.

All user-defined functions are treated as deterministic unless they are declared NOT DETERMINISTIC. Deterministic functions return a consistent result for the same parameters and are free of side effects. That is, the database server assumes that two successive calls to the same function with the same parameters will return the same result without unwanted side-effects on the semantics of the query.

To modify a user-defined function, or to hide the contents of a function by scrambling its definition, use the ALTER FUNCTION statement.

Side Effects
  • Automatic commit

Standards

  • SQL—ISO/ANSI SQL compliant.

  • Sybase—Not supported by Adaptive Server Enterprise.

Permissions

For function to be owned by self – Requires the CREATE PROCEDURE system privilege.

For function to be owned by any user – Requires one of:
  • CREATE ANY PROCEDURE system privilege.
  • CREATE ANY OBJECT system privilege.
To create a function containing an external reference, regardless of whether or not they are the owner of the function, also requires the CREATE EXTERNAL REFERENCE system privilege.