Oracle PLSQL procedures Training Institutes in Hyderabad

PL/SQL Procedure

 

Oracle / PLSQL: Procedures

This Oracle tutorial explains how to create and drop procedures in Oracle/PLSQL with syntax and examples.

Create Procedure

Just as you can in other languages, you can create your own procedures in Oracle.

Syntax

The syntax to create a procedure in Oracle is:

CREATE [OR REPLACE] PROCEDURE procedure_name
    [ (parameter [,parameter]) ]

IS
    [declaration_section]

BEGIN
    executable_section

[EXCEPTION
    exception_section]

END [procedure_name];

When you create a procedure or function, you may define parameters. There are three types of parameters that can be declared:

  1. IN - The parameter can be referenced by the procedure or function. The value of the parameter can not be overwritten by the procedure or function.
  2. OUT - The parameter can not be referenced by the procedure or function, but the value of the parameter can be overwritten by the procedure or function.
  3. IN OUT - The parameter can be referenced by the procedure or function and the value of the parameter can be overwritten by the procedure or function.

Example

Let's look at an example of how to create a procedure in Oracle.

The following is a simple example of a procedure:

CREATE OR REPLACE Procedure UpdateCourse
   ( name_in IN varchar2 )

IS
   cnumber number;

   cursor c1 is
   SELECT course_number
    FROM courses_tbl
    WHERE course_name = name_in;

BEGIN

   open c1;
   fetch c1 into cnumber;

   if c1%notfound then
      cnumber := 9999;
   end if;

   INSERT INTO student_courses
   ( course_name,
     course_number )
   VALUES
   ( name_in,
     cnumber );

   commit;

   close c1;

EXCEPTION
WHEN OTHERS THEN
   raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END;

This procedure is called UpdateCourse. It has one parameter called name_in. The procedure will lookup the course_number based on course name. If it does not find a match, it defaults the course number to 99999. It then inserts a new record into the student_courses table.

Drop Procedure

Once you have created your procedure in Oracle, you might find that you need to remove it from the database.

Syntax

The syntax to a drop a procedure in Oracle is:

DROP PROCEDURE procedure_name;
procedure_name
The name of the procedure that you wish to drop.

Example

Let's look at an example of how to drop a procedure in Oracle.

For example:

DROP PROCEDURE UpdateCourse;

This example would drop the procedure called UpdateCourse.

 

 

The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or more specific tasks. It is just like procedures in other programming languages.

The procedure contains a header and a body.

  • Header: The header contains the name of the procedure and the parameters or variables passed to the procedure.
  • Body: The body contains a declaration section, execution section and exception section similar to a general PL/SQL block.

How to pass parameters in procedure:

When you want to create a procedure or function, you have to define parameters .There is three ways to pass parameters in procedure:

  1. IN parameters: The IN parameter can be referenced by the procedure or function. The value of the parameter cannot be overwritten by the procedure or the function.
  2. OUT parameters: The OUT parameter cannot be referenced by the procedure or function, but the value of the parameter can be overwritten by the procedure or function.
  3. INOUT parameters: The INOUT parameter can be referenced by the procedure or function and the value of the parameter can be overwritten by the procedure or function.

A procedure may or may not return any value.

PL/SQL Create Procedure

Syntax for creating procedure:

  1. CREATE [OR REPLACEPROCEDURE procedure_name
  2.     [ (parameter [,parameter]) ]
  3. IS
  4.     [declaration_section]
  5. BEGIN
  6.     executable_section
  7. [EXCEPTION
  8.     exception_section]
  9. END [procedure_name];

Create procedure example

In this example, we are going to insert record in user table. So you need to create user table first.

Table creation:

  1. create table user(id number(10) primary key,name varchar2(100));

Now write the procedure code to insert record in user table.

Procedure Code:

  1. create or replace procedure "INSERTUSER"
  2. (id IN NUMBER,
  3. name IN VARCHAR2)
  4. is
  5. begin
  6. insert into user values(id,name);
  7. end;
  8. /

Output:

Procedure created.

PL/SQL program to call procedure

Let's see the code to call above created procedure.

  1. BEGIN
  2.    insertuser(101,'Rahul');
  3.    dbms_output.put_line('record inserted successfully');
  4. END;
  5. /

Now, see the "USER" table, you will see one record is inserted.

ID Name
101 Rahul

PL/SQL Drop Procedure

Syntax for drop procedure

  1. DROP PROCEDURE procedure_name;

Example of drop procedure

  1. DROP PROCEDURE pro1;

 

PL/SQL Function

The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between procedure and a function is, a function must always return a value, and on the other hand a procedure may or may not return a value. Except this, all the other things of PL/SQL procedure are true for PL/SQL function too.

Syntax to create a function:

  1. CREATE [OR REPLACEFUNCTION function_name [parameters]
  2. [(parameter_name [IN | OUT | IN OUT] type [, ...])]
  3. RETURN return_datatype
  4. {IS | AS}
  5. BEGIN
  6.    < function_body >
  7. END [function_name];

Here:

  • Function_name: specifies the name of the function.
  • [OR REPLACE] option allows modifying an existing function.
  • The optional parameter list contains name, mode and types of the parameters.
  • IN represents that value will be passed from outside and OUT represents that this parameter will be used to return a value outside of the procedure.

The function must contain a return statement.

  • RETURN clause specifies that data type you are going to return from the function.
  • Function_body contains the executable part.
  • The AS keyword is used instead of the IS keyword for creating a standalone function.

PL/SQL Function Example

Let's see a simple example to create a function.

  1. create or replace function adder(n1 in number, n2 in number)
  2. return number
  3. is
  4. n3 number(8);
  5. begin
  6. n3 :=n1+n2;
  7. return n3;
  8. end;
  9. /

Now write another program to call the function.

  1. DECLARE
  2.    n3 number(2);
  3. BEGIN
  4.    n3 := adder(11,22);
  5.    dbms_output.put_line('Addition is: ' || n3);
  6. END;
  7. /

Output:

Addition is: 33
Statement processed.
0.05 seconds

Another PL/SQL Function Example

Let's take an example to demonstrate Declaring, Defining and Invoking a simple PL/SQL function which will compute and return the maximum of two values.

  1. DECLARE
  2.    a number;
  3.    b number;
  4.    c number;
  5. FUNCTION findMax(x IN number, y IN number)
  6. RETURN number
  7. IS
  8.     z number;
  9. BEGIN
  10.    IF x > y THEN
  11.       z:= x;
  12.    ELSE
  13.       Z:= y;
  14.    END IF;
  15.    RETURN z;
  16. END;
  17. BEGIN
  18.    a:= 23;
  19.    b:= 45;
  20.    c := findMax(a, b);
  21.    dbms_output.put_line(' Maximum of (23,45): ' || c);
  22. END;
  23. /

Output:

Maximum of (23,45): 45
Statement processed.
0.02 seconds

PL/SQL function example using table

Let's take a customer table. This example illustrates creating and calling a standalone function. This function will return the total number of CUSTOMERS in the customers table.

Create customers table and have records in it.

Customers
Id Name Department Salary
1 alex web developer 35000
2 ricky program developer 45000
3 mohan web designer 35000
4 dilshad database manager 44000

Create Function:

  1. CREATE OR REPLACE FUNCTION totalCustomers
  2. RETURN number IS
  3.    total number(2) := 0;
  4. BEGIN
  5.    SELECT count(*) into total
  6.    FROM customers;
  7.     RETURN total;
  8. END;
  9. /

After the execution of above code, you will get the following result.

Function created.

Calling PL/SQL Function:

While creating a function, you have to give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. Once the function is called, the program control is transferred to the called function.

After the successful completion of the defined task, the call function returns program control back to the main program.

To call a function you have to pass the required parameters along with function name and if function returns a value then you can store returned value. Following program calls the function totalCustomers from an anonymous block:

  1. DECLARE
  2.    c number(2);
  3. BEGIN
  4.    c := totalCustomers();
  5.    dbms_output.put_line('Total no. of Customers: ' || c);
  6. END;
  7. /

After the execution of above code in SQL prompt, you will get the following result.

Total no. of Customers: 4
PL/SQL procedure successfully completed.

PL/SQL Recursive Function

You already know that a program or a subprogram can call another subprogram. When a subprogram calls itself, it is called recursive call and the process is known as recursion.

Example to calculate the factorial of a number

Let's take an example to calculate the factorial of a number. This example calculates the factorial of a given number by calling itself recursively.

  1. DECLARE
  2.    num number;
  3.    factorial number;
  4. FUNCTION fact(x number)
  5. RETURN number
  6. IS
  7.    f number;
  8. BEGIN
  9.    IF x=0 THEN
  10.       f := 1;
  11.    ELSE
  12.       f := x * fact(x-1);
  13.    END IF;
  14. RETURN f;
  15. END;
  16. BEGIN
  17.    num:= 6;
  18.    factorial := fact(num);
  19.    dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
  20. END;
  21. /

After the execution of above code at SQL prompt, it produces the following result.

Factorial 6 is 720
PL/SQL procedure successfully completed.

PL/SQL Drop Function

Syntax for removing your created function:

If you want to remove your created function from the database, you should use the following syntax.

  1. DROP FUNCTION function_name;