Introduction
​​The stored procedure in PL/SQL is a program block that performs specific tasks. It can be considered a function or a method. But the procedure does not return a value directly like functions. It can be invoked by triggers or other procedures etc. It reduces the network traffic and increases performance because the commands in the stored procedure are executed as a single batch of code.
It consists of two parts.
- Header: The header includes the name of the procedure and the parameters passed to the procedure.
- Body: Body includes declaration section, execution section, and exception section.
Create Procedure
Syntax
CREATE [OR REPLACE] PROCEDURE procedure_name [list of parameters] IS | AS //Declaration block BEGIN //Execution block EXCEPTION //Exception block END; |
- Declaration Block: It is an optional block. It contains cursors, constants, variables, exceptions, and nested subprograms. These things are local to the subprogram and cease to exist when the subprogram completes execution.
- Executable Block: This is a mandatory block and contains statements that perform the designated action.
- Exception Block: This is again an optional block. It includes the code that handles run-time errors.
Modes of Parameters
- IN-parameters: IN mode parameters are read-only parameters. The procedure cannot change the value of IN parameters.
- OUT-parameters: OUT mode parameters are the write-only parameters used to return values to the calling program. The procedure can change the value of OUT parameters.
- IN OUT-parameters: IN OUT mode parameters are both read and write parameters, i.e., a procedure can read and change the IN OUT parameter value and return it to the calling program.
Example
In this example, we create a procedure named add_employee to add new employee data in the Employee table. The employeeID and name are taken as IN mode parameters in the procedure.
CREATE OR REPLACE PROCEDURE add_employee(employeeID IN NUMBER, name IN VARCHAR2) IS BEGIN insert into Employee values(employeeID, name); END; |
Output
Recommended topics, procedure call in compiler design and Tcl Commands in SQL