Procedure - (Oracle Advanced)
In Oracle, a procedure is a named PL/SQL block that performs a specific task. It can take input arguments and return output values, and can be called from other PL/SQL blocks or SQL statements. Procedures are commonly used to encapsulate reusable code and simplify complex tasks.
Syntax
The syntax for creating a procedure in Oracle is as follows:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
IS
-- Declaration statements
BEGIN
-- Execution statements
[EXCEPTION
-- Exception handling statements]
END;
Here, procedure_name
is the name of the procedure, parameter_name
is the name of an input or output parameter, and type
is the data type of the parameter. The [OR REPLACE]
clause is optional and allows you to replace an existing procedure with the same name.
Example
Here is an example of a simple procedure that takes in two integer values and returns their sum:
CREATE PROCEDURE sum_proc(x IN NUMBER, y IN NUMBER, s OUT NUMBER)
IS
BEGIN
s:= x + y;
END;
In this example, sum_proc
is the name of the procedure, and x
, y
, and s
are parameters with types NUMBER
. The IN
keyword indicates that x
and y
are input parameters, and the OUT
keyword indicates that s
is an output parameter. The BEGIN
and END
keywords enclose the body of the procedure, where s
is set equal to the sum of x
and y
.
Output
To call the sum_proc
procedure, you can execute the following SQL statement:
DECLARE
a NUMBER;
BEGIN
sum_proc(3, 5, a);
DBMS_OUTPUT.PUT_LINE('Sum = ' || a);
END;
This will output Sum = 8
to the console.
Explanation
In the above example, we have defined a procedure called sum_proc
that takes in two integer values and returns their sum. We then call the sum_proc
procedure and pass in the parameters 3
and 5
. The result is stored in the variable a
, which we then print out to the console using the DBMS_OUTPUT.PUT_LINE
procedure.
Use
Procedures are a powerful feature of Oracle that allow you to encapsulate complex business logic and simplify tasks. They are often used in database management systems, and can be called from other PL/SQL blocks or SQL statements.
Important Points
- A procedure is a named PL/SQL block that performs a specific task.
- Procedures can take input arguments and return output values, and can be called from other PL/SQL blocks or SQL statements.
- Procedures are used to encapsulate reusable code and simplify complex tasks.
Summary
In summary, procedures are a powerful feature of Oracle that allow you to encapsulate complex business logic and simplify tasks. They are defined using the CREATE PROCEDURE
statement and can take input arguments and return output values. Procedures are often used in database management systems to encapsulate reusable code.