PLSQL Functions
PLSQL Functions
For example, let’s create a function called ''employer_details_func' similar to the one created in
stored proc
employee_name := employer_details_func;
If ‘employee_name’ is of datatype varchar we can store the name of the employee by assigning
the return type of the function to it.
dbms_output.put_line(employer_details_func);
This line displays the value returned by the function.
The following program calculates the factorial of a given number by calling itself recursively −
DECLARE
num number;
factorial number;
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Factorial 6 is 720
PL/SQL procedure successfully completed.
Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL Function
that computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 21;
b:= 40;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (21,40): ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Maximum of (21,40): 40