The CREATE FUNCTION statement (create_function_statement) defines a database function.
<create_function_statement> ::= CREATE [PUBLIC] FUNCTION <dbfunction_name> [(<formal_parameter1>,..)] RETURNS <data_type> AS <routine>
<formal_parameter1> ::= <argument1>
<data_type>
<argument1> ::= <identifier>
This database function determines the average price for single rooms in hotels that are located within the specified zip code range.
CREATE FUNCTION avg_price (zip CHAR(5)) RETURNS
FIXED(6,2) AS
VAR summe FIXED(10,2); price FIXED(6,2);
hotels INTEGER; avg_price FIXED(6,2);
TRY
SET sum = 0; SET hotels = 0;
SELECT price FROM mona.room,mona.hotel WHERE zip = :zip AND
room.hno = hotel.hno AND type = 'single';
WHILE $rc = 0 DO BEGIN
FETCH INTO :price;
SET sum = sum + price;
SET hotels = hotels + 1;
END;
CATCH
IF $rc <> 100 THEN STOP ($rc, 'unexpected error');
IF hotels > 0 THEN RETURN sum/hotels
ELSE RETURN NULL;
If a schema is not specified in the database function name, the current schema is assumed implicitly.
The database function is assigned to the schema that has been determined implicitly or specified explicitly. The current user must have the CREATEIN privilege for this schema. The function name must differ from the names of the database functions that already exist in the schema.
The current user is the owner of a database function. This user has the EXECUTE privilege to execute the database function and assign this authorization to other users.
By specifying an argument argument1, you assign a name to a formal parameter of the database function. This parameter name can then be used as a variable in expressions and assignments in the database function.
Only BOOLEAN, CHAR[ACTER], DATE, FIXED, FLOAT, INT[EGER], NUMBER, REAL, SMALLINT, TIME, TIMESTAMP, and VARCHAR can be used as the data type (data_type) of a formal parameter of a database function.
Data types are normally defined with both length and precision. However, if you specify VARCHAR or NUMBER without length or precision, the database system derives these properties automatically, depending on the context of the function call.
If you specify PUBLIC, a global database function, which can be called without specifying a schema name, is generated. In this scenario, the function name must not contain a schema name and it must not be the same as the name of another global database function.
Only BOOLEAN, CHAR[ACTER], DATE, DEC[IMAL], DOUBLE, FLOAT, INT[EGER], NUMBER, NUMERIC, REAL, SMALLINT,TIME, TIMESTAMP, and VARCHAR can be used as the data type of the return code.