Tuesday 2 April 2013

PL/SQL Procedures


What is a Stored Procedure?
---------------------------

A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific task.
This is similar to a procedure in other programming languages. A procedure has a header and a body.
The header consists of the name of the procedure and the parameters or variables passed to the procedure.
 The body consists or declaration section, execution section and exception section similar to a general PL/SQL Block.
 A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.

We can pass parameters to procedures in three ways.
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters

A procedure may or may not return any value.By using OUT parameter we can return more values.


Ex: 1:-

PROCEDURE raise_salary (emp_id INTEGER, amount REAL) IS
   current_salary REAL;
   salary_missing EXCEPTION;
BEGIN
   SELECT sal INTO current_salary FROM emp
      WHERE empno = emp_id;
   IF current_salary IS NULL THEN
      RAISE salary_missing;
   ELSE
      UPDATE emp SET sal = sal + amount
         WHERE empno = emp_id;
   END IF;
EXCEPTION
   WHEN NO_DATA_FOUND THEN
      INSERT INTO emp_audit VALUES (emp_id, 'No such number');
   WHEN salary_missing THEN
      INSERT INTO emp_audit VALUES (emp_id, 'Salary is null');
END raise_salary;


How to execute a Stored Procedure?
----------------------------------------------

There are two ways to execute a procedure.

1) From the SQL prompt.

 EXECUTE [or EXEC] procedure_name;

2) Within another procedure – simply use the procedure name.

  procedure_name;



Ur's
AmarAlam

0 comments:

Post a Comment