Show List
Stored Procedures and Functions
Stored procedures and functions in PL/SQL are reusable blocks of code that encapsulate business logic. They allow developers to perform specific tasks, enhance code reusability, and improve application performance by executing logic directly on the database server.
1. What are Procedures and Functions?
Stored Procedure:
- A named PL/SQL block that performs a specific task.
- Does not necessarily return a value.
- Often used to execute a series of SQL statements or operations.
Function:
- A named PL/SQL block that always returns a value.
- Primarily used for computations and returning a single result.
2. Differences Between Procedures and Functions
Feature | Stored Procedure | Function |
---|---|---|
Purpose | Performs a task or a series of operations. | Returns a single value or result. |
Return Value | Optional (can use OUT parameters). | Mandatory (uses the RETURN statement). |
Invocation | Can be called independently. | Typically used within SQL statements or PL/SQL. |
Usage in SQL | Cannot be called directly in SQL statements. | Can be used in SQL queries (if deterministic). |
3. Creating and Executing Procedures
Syntax:
Example: Creating a Procedure to Insert Employee Data
Executing the Procedure:
4. Creating and Executing Functions
Syntax:
Example: Creating a Function to Calculate Bonus
Executing the Function:
Using a Function in a SQL Query:
5. Parameter Modes: IN, OUT, IN OUT
Parameter Mode | Description |
---|---|
IN | Default mode. The parameter is passed into the procedure or function. |
OUT | Used to return a value to the calling program. |
IN OUT | Allows a parameter to be passed into and out of the procedure or function. |
Examples:
IN Parameter:
Execution:
OUT Parameter:
Execution:
IN OUT Parameter:
Execution:
6. Example: Procedure for Inserting Employee Data
Procedure Code:
Execution:
Summary
Topic | Key Points |
---|---|
Procedures | Perform tasks but do not necessarily return values. |
Functions | Always return a value, suitable for calculations and SQL queries. |
Parameter Modes | IN (input), OUT (output), IN OUT (both input and output). |
Example Application | Procedure for inserting employee data demonstrates practical use of IN parameters and error handling. |
Mastering procedures and functions helps in creating modular, efficient, and reusable code for complex database operations.
Leave a Comment