8/8/2019 Les09 Creating Procedures
1/36
Copyright Oracle Corporation, 2001. All rights reserved.
Creating Procedures
8/8/2019 Les09 Creating Procedures
2/36
9-2 Copyright Oracle Corporation, 2001. All rights reserved.
Objectives
After completing this lesson, you should be able todo the following:
Distinguish anonymous PL/SQL blocks from
named PL/SQL blocks (subprograms)
Describe subprograms
List the benefits of using subprograms
List the different environments from which
subprograms can be invoked
8/8/2019 Les09 Creating Procedures
3/36
9-3 Copyright Oracle Corporation, 2001. All rights reserved.
Objectives
After completing this lesson, you should be able todo the following: Describe PL/SQL blocks and subprograms Describe the uses of procedures
Create procedures Differentiate between formal and actual parameters List the features of different parameter modes Create procedures with parameters
Invoke a procedure Handle exceptions in procedures Remove a procedure
8/8/2019 Les09 Creating Procedures
4/36
9-4 Copyright Oracle Corporation, 2001. All rights reserved.
PL/SQL Program Constructs
orDECLARE
BEGIN
EXCEPTION
END;
IS|AS
Tools ConstructsAnonymous blocks
Application procedures or
functions
Application packages
Application triggers
Object types
Database Server
ConstructsAnonymous blocks
Stored procedures or
functionsStored packages
Database triggers
Object types
8/8/2019 Les09 Creating Procedures
5/36
9-5 Copyright Oracle Corporation, 2001. All rights reserved.
Overview of Subprograms
A subprogram:
Is a named PL/SQL block that can accept parametersand be invoked from a calling environment
Is of two types: A procedure that performs an action
A function that computes a value
Is based on standard PL/SQL block structure
Provides modularity, reusability, extensibility,
and maintainability Provides easy maintenance, improved data security
and integrity, improved performance, and improvedcode clarity
8/8/2019 Les09 Creating Procedures
6/36
9-6 Copyright Oracle Corporation, 2001. All rights reserved.
Block Structure for Anonymous
PL/SQL Blocks
DECLARE (optional)Declare PL/SQL objects to be usedwithin this block
BEGIN (mandatory)Define the executable statements
EXCEPTION (optional)Define the actions that take place ifan error or exception arises
END; (mandatory)
8/8/2019 Les09 Creating Procedures
7/36
9-7 Copyright Oracle Corporation, 2001. All rights reserved.
Block Structure for PL/SQL Subprograms
IS |AS
Declaration section
BEGIN
Executable section
EXCEPTION (optional)
Exception sectionEND;
Subprogram Specification
SubprogramBody
8/8/2019 Les09 Creating Procedures
8/36
9-8 Copyright Oracle Corporation, 2001. All rights reserved.
Benefits of Subprograms
Easy maintenance
Improved data security and integrity
Improved performance
Improved code clarity
8/8/2019 Les09 Creating Procedures
9/36
9-9 Copyright Oracle Corporation, 2001. All rights reserved.
Developing Subprograms by Using
iSQL*Plus
2 3
4
1
8/8/2019 Les09 Creating Procedures
10/36
9-10 Copyright Oracle Corporation, 2001. All rights reserved.
What Is a Procedure?
A procedure is a type of subprogram that performsan action.
A procedure can be stored in the database, as a
schema object, for repeated execution.
8/8/2019 Les09 Creating Procedures
11/36
9-11 Copyright Oracle Corporation, 2001. All rights reserved.
Syntax for Creating Procedures
CREATE [OR REPLACE] PROCEDUREprocedure_name[(parameter1 [mode1] datatype1,parameter2[mode2] datatype2,. . .)]
IS|ASPL/SQL Block;
The REPLACE option indicates that if the procedureexists, it will be dropped and replaced with thenew version created by the statement.
PL/SQL block starts with eitherBEGIN or thedeclaration of local variables and ends with eitherEND orEND procedure_name.
8/8/2019 Les09 Creating Procedures
12/36
9-12 Copyright Oracle Corporation, 2001. All rights reserved.
Developing Procedures
1
Editor
Code to createprocedure
fil
e.sql
iSQL*Plus
2 Load and execute file.sql
Oracle Source code
Compile
P code
Use SHOW ERRORSto view
compilation errorsProcedure
created
Execute 3
8/8/2019 Les09 Creating Procedures
13/36
9-13 Copyright Oracle Corporation, 2001. All rights reserved.
Formal Versus Actual ParametersFormal Versus Actual Parameters
Formal parameters: variables declared in theparameter list of a subprogram specification
Example:
CREATE PROCEDURE raise_sal(p_idNUMBER,p_amountNUMBER)
...
END raise_sal;
Actual parameters: variables or expressionsreferenced in the parameter list of a subprogram call
Example:
raise_sal(v_id, 2000)
Formal parameters: variables declared in theparameter list of a subprogram specification
Example:
CREATE PROCEDURE raise_sal(p_idNUMBER,p_amountNUMBER)
...
END raise_sal;
Actual parameters: variables or expressionsreferenced in the parameter list of a subprogram call
Example:
raise_sal(v_id, 2000)
8/8/2019 Les09 Creating Procedures
14/36
9-14 Copyright Oracle Corporation, 2001. All rights reserved.
Procedural Parameter Modes
Calling
environment
Procedure
(DECLARE)
BEGIN
EXCEPTION
END;
IN parameter
OUT parameter
IN OUT parameter
8/8/2019 Les09 Creating Procedures
15/36
9-15 Copyright Oracle Corporation, 2001. All rights reserved.
Creating Procedures with Parameters
Can be assigned a defaultvalue
Actual parameter can be aliteral, expression,
constant, or initializedvariable
Initialized variableUninitializedvariable
Formal parameter acts asa constant
Passed intosubprogram;returned to calling
environment
Returned tocallingenvironment
Value is passed intosubprogram
Default mode
IN OUTOUTIN
Must be specified
Must be a variable
Must be specified
Must be a variable
Cannot beassigneda default value
Cannot beassigneda default value
8/8/2019 Les09 Creating Procedures
16/36
9-16 Copyright Oracle Corporation, 2001. All rights reserved.
IN Parameters: Example
p_id176
CREATE OR REPLACE PROCEDURE raise_salary(p_id IN employees.employee_id%TYPE)
ISBEGINUPDATE employeesSET salary = salary * 1.10 WHERE employee_id = p_id;END raise_salary;
/
8/8/2019 Les09 Creating Procedures
17/36
9-17 Copyright Oracle Corporation, 2001. All rights reserved.
OUT Parameters: Example
Calling environment QUERY_EMP procedure
p_id
p_name
p_salary
p_comm
171
SMITH
7400
0.15
8/8/2019 Les09 Creating Procedures
18/36
9-18 Copyright Oracle Corporation, 2001. All rights reserved.
OUT Parameters: ExampleOUT Parameters: Example
CREATE OR REPLACE PROCEDURE query_emp(p_id IN employees.employee_id%TYPE, p_name OUT employees.last_name%TYPE, p_salary OUT employees.salary%TYPE, p_comm OUT employees.commission_pct%TYPE)
ISBEGINSELECT last_name, salary, commission_pctINTO p_name, p_salary, p_commFROM employees WHERE employee_id = p_id;
END query_emp;/
emp_query.sqlemp_query.sql
8/8/2019 Les09 Creating Procedures
19/36
9-19 Copyright Oracle Corporation, 2001. All rights reserved.
Viewing OUT Parameters
Load and run the emp_query.sql script file tocreate the QUERY_EMP procedure.
Declare host variables, execute the QUERY_EMPprocedure, and print the value of the global G_NAMEvariable.
VARIABLE g_name VARCHAR2(25)VARIABLE g_sal NUMBER VARIABLE g_comm NUMBER
EXECUTE query_emp(171, :g_name, :g_sal, :g_comm)
PRINT g_name
8/8/2019 Les09 Creating Procedures
20/36
9-20 Copyright Oracle Corporation, 2001. All rights reserved.
IN OUT Parameters
Calling environment FORMAT_PHONE procedure
p_phone_no'(800)633-0575''8006330575'
CREATE OR REPLACE PROCEDURE format_phone(p_phone_no IN OUT VARCHAR2)
ISBEGINp_phone_no := '(' || SUBSTR(p_phone_no,1,3) ||
')' || SUBSTR(p_phone_no,4,3) ||'-' || SUBSTR(p_phone_no,7);END format_phone;/
8/8/2019 Les09 Creating Procedures
21/36
9-21 Copyright Oracle Corporation, 2001. All rights reserved.
Viewing IN OUT Parameters
VARIABLE g_phone_no VARCHAR2(15)BEGIN:g_phone_no := '8006330575';
END;/
PRINT g_phone_noEXECUTE format_phone (:g_phone_no)PRINT g_phone_no
8/8/2019 Les09 Creating Procedures
22/36
9-22 Copyright Oracle Corporation, 2001. All rights reserved.
Methods for Passing Parameters
Positional: List actual parameters in the sameorder as formal parameters.
Named: List actual parameters in arbitrary order
by associating each with its corresponding formalparameter.
Combination: List some of the actual parametersas positional and some as named.
8/8/2019 Les09 Creating Procedures
23/36
9-23 Copyright Oracle Corporation, 2001. All rights reserved.
DEFAULT Option for Parameters
CREATE OR REPLACE PROCEDURE add_dept(p_name IN departments.department_name%TYPE
DEFAULT 'unknown', p_loc IN departments.location_id%TYPE
DEFAULT 1700)ISBEGININSERT INTO departments(department_id,
department_name, location_id)VALUES (departments_seq.NEXTVAL, p_name, p_loc);END add_dept;/
8/8/2019 Les09 Creating Procedures
24/36
9-24 Copyright Oracle Corporation, 2001. All rights reserved.
Examples of Passing Parameters
BEGINadd_dept;add_dept ('TRAINING', 2500);add_dept ( p_loc => 2400, p_name =>'EDUCATION');add_dept ( p_loc => 1200) ;
END;/
SELECT department_id, department_name, location_idFROM departments;
8/8/2019 Les09 Creating Procedures
25/36
9-25 Copyright Oracle Corporation, 2001. All rights reserved.
Declaring Subprograms
CREATE OR REPLACE PROCEDURE leave_emp2(p_id IN employees.employee_id%TYPE)
ISPROCEDURE log_exec
ISBEGININSERT INTO log_table (user_id, log_date)VALUES (USER, SYSDATE);END log_exec;
BEGIN
DELETE FROM employeesWHERE employee_id = p_id;log_exec;
END leave_emp2;/
leave_emp2.sqlleave_emp2.sql
8/8/2019 Les09 Creating Procedures
26/36
8/8/2019 Les09 Creating Procedures
27/36
9-27 Copyright Oracle Corporation, 2001. All rights reserved.
Invoking a Procedure from Another
Procedure
Invoking a Procedure from Another
Procedure
CREATE OR REPLACE PROCEDURE process_empsIS
CURSOR emp_cursor ISSELECT employee_idFROM employees;
BEGINFOR emp_rec IN emp_cursorLOOPraise_salary(emp_rec.employee_id);
END LOOP;COMMIT;
END process_emps;/
process_emps.sqlprocess_emps.sql
8/8/2019 Les09 Creating Procedures
28/36
9-28 Copyright Oracle Corporation, 2001. All rights reserved.
Handled Exceptions
PROCEDUREPROC2 ...IS...
BEGIN...EXCEPTION...END PROC2;
Called procedure
Calling procedure
PROCEDUREPROC1 ...
IS...BEGIN...PROC2(arg1);
...EXCEPTION
...END PROC1;
Exception raised
Exception handled
Control returns to
calling procedure
8/8/2019 Les09 Creating Procedures
29/36
9-29 Copyright Oracle Corporation, 2001. All rights reserved.
Unhandled Exceptions
PROCEDUREPROC2 ...IS...
BEGIN...EXCEPTION...END PROC2;
Called procedure
Exception raised
PROCEDUREPROC1 ...IS...BEGIN...PROC2(arg1);
...EXCEPTION...
END PROC1;
Calling procedure
Exception unhandled
Control returned toexception section of
calling procedure
8/8/2019 Les09 Creating Procedures
30/36
9-30 Copyright Oracle Corporation, 2001. All rights reserved.
Removing ProceduresRemoving Procedures
Drop a procedure stored in the database.Drop a procedure stored in the database.
Syntax:
Example:
Syntax:
Example:
DROP PROCEDUREprocedure_name
DROP PROCEDURE raise_salary;
8/8/2019 Les09 Creating Procedures
31/36
9-31 Copyright Oracle Corporation, 2001. All rights reserved.
Summary
In this lesson, you should have learned that:
A procedure is a subprogram that performs anaction.
You create procedures by using the CREATE
PROCEDURE command. You can compile and save a procedure in the
database.
Parameters are used to pass data from the callingenvironment to the procedure.
There are three parameter modes: IN, OUT, and INOUT.
8/8/2019 Les09 Creating Procedures
32/36
9-32 Copyright Oracle Corporation, 2001. All rights reserved.
Summary
Local subprograms are programs that are definedwithin the declaration section of another program.
Procedures can be invoked from any tool or
language that supports PL/SQL. You should be aware of the effect of handled and
unhandled exceptions on transactions and callingprocedures.
You can remove procedures from the database by
using the DROP PROCEDURE command. Procedures can serve as building blocks for an
application.
8/8/2019 Les09 Creating Procedures
33/36
9-33 Copyright Oracle Corporation, 2001. All rights reserved.
Practice 9Overview
This practice covers the following topics:
Creating stored procedures to: Insert new rows into a table, using the supplied
parameter values Update data in a table for rows matching with the
supplied parameter values
Delete rows from a table that match the suppliedparameter values
Query a table and retrieve data based on suppliedparameter values
Handling exceptions in procedures
Compiling and invoking procedures
8/8/2019 Les09 Creating Procedures
34/36
9-34 Copyright Oracle Corporation, 2001. All rights reserved.
8/8/2019 Les09 Creating Procedures
35/36
9-35 Copyright Oracle Corporation, 2001. All rights reserved.
8/8/2019 Les09 Creating Procedures
36/36
9-36 Copyright Oracle Corporation, 2001. All rights reserved.