Function - (PL/SQL Function)
A PL/SQL function is a named block that performs a specific task and returns a value. It can be used within SQL statements or other PL/SQL blocks. It is similar to a procedure, except that it returns a value.
Syntax
The basic syntax for creating a PL/SQL function is as follows:
FUNCTION function_name (parameter1 datatype, parameter2 datatype, ...) RETURN return_type IS
variable1 datatype;
variable2 datatype;
BEGIN
-- PL/SQL code goes here
RETURN value;
END;
Here, function_name
is the name of the function, return_type
is the data type of the value that the function returns, and parameter1
, parameter2
, and so on are the input parameters to the function.
Example
Here is an example of a PL/SQL function that takes two parameters and returns their sum:
FUNCTION add_numbers (num1 NUMBER, num2 NUMBER) RETURN NUMBER IS
total NUMBER;
BEGIN
total := num1 + num2;
RETURN total;
END;
Output
A PL/SQL function does not produce output on its own. The output is the value returned by the function, which can be used in other SQL statements or PL/SQL blocks.
Explanation
In the above example, we have created a function called add_numbers
that takes two parameters (num1
and num2
) of type NUMBER and returns their sum, which is also of type NUMBER. The function first declares a local variable called total
of type NUMBER, which is used to store the sum of the two parameters. The RETURN
statement is then used to return the value of total
.
Use
PL/SQL functions can be used in SQL statements and other PL/SQL blocks just like any other function. They are useful for performing complex calculations or operations that are used repeatedly throughout an application.
Important Points
- PL/SQL functions are named blocks that return a value.
- They can be used within SQL statements or other PL/SQL blocks.
- They can take input parameters, and their output is the value returned by the function.
- They are useful for performing complex calculations or operations that are used repeatedly throughout an application.
Summary
In summary, a PL/SQL function is a named block that performs a specific task and returns a value. It can take input parameters and its output is the value returned by the function. Functions are useful for performing complex calculations or operations that are used repeatedly throughout an application.