Database Management Systems (2130703)

BE | Semester-3   Summer-2018 | 05/23/2018

Q4) (c)

Explain stored procedure with proper example.

  • A stored procedure (proc) is a group of PL/SQL statements that performs specific task.
  • A procedure has two parts, header and body.
  • The header consists of the name of the procedure and the parameters passed to the procedure.
  • The body consists of declaration section, execution section and exception section.
  • A procedure may or may not return any value. A procedure may return more than one value.

General Syntax to create a procedure

  CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
  IS
    Declaration section
  BEGIN
    Execution section
  EXCEPTION
    Exception section
  END;

Explanation

Create:-It will create a procedure.
Replace:- It will re-create a procedure if it already exists.
We can pass parameters to the procedures in three ways.
  1. IN-parameters: - These types of parameters are used to send values to stored procedures.
  2. OUT-parameters: - These types of parameters are used to get values from stored procedures. This is similar to a return type in functions but procedure can return values for more than one parameters.
  3. IN OUT-parameters: - This type of parameter allows us to pass values into a procedure and get output values from the procedure.
IS indicates the beginning of the body of the procedure. The code between IS and BEGIN forms the Declaration section.
Begin:-It contains the executable statement.
Exception:- It contains exception handling part. This section is optional.
End:- It will end the procedure.

The syntax within the brackets [ ] indicates that they are optional. By using CREATE OR REPLACE together the procedure is created if it does not exist and if it exists then it is replaced with the current code.

How to execute a Stored Procedure?

There are two ways to execute a procedure.
  1. From the SQL prompt.
    Syntax: EXECUTE [or EXEC] procedure_name (parameter);
  2. Within another procedure – simply use the procedure name.
    Syntax: procedure_name (parameter);

Example 1 (Using IN)

  CREATE OR REPLACE PROCEDURE get_studentname_by_id (id IN NUMBER)
  IS
  BEGIN
    SELECT studentname
    FROM stu_tbl
    WHERE studentID = id;
  END;

Execute:-

  EXECUTE get_studentname_by_id(10);
    OR
  get_studentname_by_id(10);
Explanation:- Above procedure gives the name of student whose id is 10.