Creating a subfunction v14
The FUNCTION clause specified in the declaration section defines and names a subfunction local to that block.
The term block refers to the SPL block structure consisting of an optional declaration section, a mandatory executable section, and an optional exception section. Blocks are the structures for standalone procedures and functions, anonymous blocks, subprograms, triggers, packages, and object type methods.
The phrase the identifier is local to the block means that the identifier (that is, a variable, cursor, type, or subprogram) is declared in the declaration section of that block and is therefore accessible by the SPL code in the executable section and optional exception section of that block.
FUNCTION <name> [ (<parameters>) ]
RETURN <data_type>
{ IS | AS }
[ PRAGMA AUTONOMOUS_TRANSACTION; ]
[ <declarations> ]
BEGIN
<statements>
END [ <name> ];Where:
nameis the identifier of the subfunction.parametersis a list of formal parameters.data_typeis the data type of the value returned by the function’sRETURNstatement.PRAGMA AUTONOMOUS_TRANSACTIONis the directive that sets the subfunction as an autonomous transaction.declarationsare variable, cursor, type, or subprogram declarations. If subprogram declarations are included, they must be declared after all other variable, cursor, and type declarations.statementsare SPL program statements. TheBEGIN - ENDblock can contain anEXCEPTIONsection.
Examples
This example shows the use of a recursive subfunction:
DECLARE
FUNCTION factorial (
n BINARY_INTEGER
) RETURN BINARY_INTEGER
IS
BEGIN
IF n = 1 THEN
RETURN n;
ELSE
RETURN n * factorial(n-1);
END IF;
END factorial;
BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE(i || '! = ' || factorial(i));
END LOOP;
END;The following is the output:
1! = 1 2! = 2 3! = 6 4! = 24 5! = 120
- On this page
- Examples