The CREATE FUNCTION statement (create_function_statement) defines a database function.
<create_function_statement> ::= CREATE FUNCTION <dbfunction_name> [(<formal_parameter1>,..)] RETURNS <data_type> AS <routine>
<formal_parameter1> ::= <argument1>
<data_type>
<argument1> ::= <identifier>
dbfunction_name, data_type, routine, 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 sum FIXED(10,2); price FIXED(6,2);
hotels INTEGER; avg_price FIXED(6,2);
TRY
SET sum = 0; SET hotels = 0;
SELECT price FROM travel.room,travel.hotel WHERE zip = :zip
AND
room.hno = hotel.hno AND roomtype = '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;
The current user is the owner of a database function. This user has the authorization to execute the database function and assign this authorization to other users.
Argument
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.
Data Type
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.
RETURNS
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.
Data Types
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.