M4 PPT 1a
M4 PPT 1a
M4 PPT 1a
4
Differences Between Anonymous Blocks
and Subprograms
• As the word “anonymous” indicates, anonymous blocks
are unnamed executable PL/SQL blocks.
• Because they are unnamed, they can neither be reused
nor stored in the database for later use.
• While you can store anonymous blocks on your PC, the
database is not aware of them, so no one else can
share them.
• Procedures and functions are PL/SQL blocks that are
named, and they are also known as subprograms.
5
Differences Between Anonymous Blocks
and Subprograms
• These subprograms are compiled and stored in the
database.
• The block structure of the subprograms is similar to
the structure of anonymous blocks.
• While subprograms can be explicitly shared, the
default is to make them private to the owner’s
schema.
• Later subprograms become the building blocks of
packages and triggers.
6
Differences Between Anonymous Blocks
and Subprograms
• Anonymous blocks
DECLARE (Optional) Variables, cursors,
etc.;
BEGIN (Mandatory)
SQL and PL/SQL statements; EXCEPTION
(Optional)
WHEN exception-handling actions; END;
(Mandatory)
• Subprograms
(procedures)
CREATE [OR REPLACE] PROCEDURE name [parameters] IS|AS (Mandatory) Variables,
cursors, etc.; (Optional)
BEGIN (Mandatory)
SQL and PL/SQL statements; EXCEPTION (Optional)
WHEN exception-handling actions; END [name]; (Mandatory)
7
Differences Between Anonymous Blocks
and Subprograms
• The alternative to an anonymous block is a named
block. How the block is named depends on what
you are creating.
• You can create :
– a named procedure (does not return values except as out
parameters)
– a function (must return a single value not including out
parameters)
– a package (groups functions and procedures together)
– a trigger
8
Differences Between Anonymous Blocks
and Subprograms
• The keyword DECLARE is replaced by CREATE
PROCEDURE procedure-name IS | AS.
• In anonymous blocks, DECLARE states, "this is the start
of a block."
• Because CREATE PROCEDURE states, "this is the start
of a subprogram," we do not need (and must not use)
DECLARE.
10 9
Differences Between Anonymous Blocks
and Subprograms
Anonymous Blocks Subprograms
Unnamed PL/SQL blocks Named PL/SQL blocks
Compiled on every execution Compiled only once, when created
10
Differences Between Anonymous Blocks
and Subprograms
• The keyword DECLARE is replaced by CREATE
PROCEDURE procedure-name IS | AS.
• In anonymous blocks, DECLARE states, "this is the start
of a block."
• Because CREATE PROCEDURE states, "this is the start
of a subprogram," we do not need (and must not use)
DECLARE.
11
Benefits of Subprograms
• Procedures and functions have many benefits due to
the modularizing of the code:
– Easy maintenance: Modifications need only be done once
to improve multiple applications and minimize testing.
– Code reuse: Subprograms are located in one place.
• When compiled and validated, they can be used and
reused in any number of applications.
12
Benefits of Subprograms
• Improved data security: Indirect access to database
objects is permitted by the granting of security
privileges on the subprograms.
• By default, subprograms run with the privileges of
the subprogram owner, not the privileges of the user.
• Data integrity: Related actions can be grouped into a
block and are performed together (“Statement
Processed”) or not at all.
13
Benefits of Subprograms
• Improved performance: You can reuse compiled PL/SQL
code that is stored in the shared SQL area cache of the
server.
• Subsequent calls to the subprogram avoid compiling
the code again.
• Also, many users can share a single copy of the
subprogram code in memory.
• Improved code clarity: By using appropriate names and
conventions to describe the action of the routines, you
can reduce the need for comments, and enhance the
clarity of the code.
14
Procedures and Functions : Similarities
• Are named PL/SQL blocks
• Are called PL/SQL subprograms
• Have block structures similar to anonymous
blocks:
– Optional parameters
– Optional declarative section (but the DECLARE keyword
changes to IS or AS)
– Mandatory executable section
– Optional section to handle exceptions
• Procedures and functions can both return data as
OUT and IN OUT parameters.
15
Procedures and Functions : Differences
• A function MUST return a value using the RETURN
statement.
• A procedure can only return a value using an OUT or an
IN OUT parameter.
• The return statement in a function returns control to the
calling program and returns the results of the function.
• The return statement within a procedure is optional. It
returns control to the calling program before all of the
procedure's code has been executed.
• Functions can be called from SQL, procedures cannot.
• Functions are considered expressions, procedures are
not.
16
What Is a Procedure?
• A procedure is a named PL/SQL block that can accept
parameters.
• Generally, you use a procedure to perform an action
(sometimes called a “side-effect”).
• A procedure is compiled and stored in the database as
a schema object.
– Shows up in USER_OBJECTS as an object type of PROCEDURE
– More details in USER_PROCEDURES
– Detailed PL/SQL code in USER_SOURCE
17
Syntax for Creating Procedures
• Parameters are optional
• Mode defaults to IN
• Datatype can be either explicit (for example,
VARCHAR2) or implicit with %TYPE
• Body is the same as an anonymous block
18
Syntax for Creating Procedures
• Use CREATE PROCEDURE followed by the name,
optional parameters, and keyword IS or AS.
• Add the OR REPLACE option to overwrite an
existing procedure.
• Write a PL/SQL block containing local variables, a
BEGIN, and an END (or END procedure_name).
20
19
Procedure: Example
• In the following example, the add_dept procedure
inserts a new department with the department_id
280 and department_name ST-Curriculum.
• The procedure declares two variables, v_dept_id and
v_dept_name, in the declarative section.
CREATE OR REPLACE PROCEDURE add_dept IS
v_dept_id dept.department_id%TYPE;
v_dept_name dept.department_name%TYPE;
BEGIN
v_dept_id := 280;
v_dept_name := 'ST-Curriculum'; dept(department_id, department_name)
INSERT INTO VALUES(v_dept_id, v_dept_name);
DBMS_OUTPUT.PUT_LINE('Inserted '|| SQL%ROWCOUNT ||'
row.’);
END;
20
Procedure: Example
• The declarative section of a procedure starts
immediately after the procedure declaration and
does not begin with the keyword DECLARE.
• This procedure uses the SQL%ROWCOUNT cursor
attribute to check if the row was successfully
inserted. SQL%ROWCOUNT should return 1 in this
case.
CREATE OR REPLACE PROCEDURE add_dept IS
v_dept_id dept.department_id%TYPE;
v_dept_name dept.department_name%TYPE;
BEGIN
v_dept_id := 280;
v_dept_name := 'ST-Curriculum';
INSERT INTO dept(department_id, department_name)
VALUES(v_dept_id, v_dept_name);
DBMS_OUTPUT.PUT_LINE('Inserted '|| SQL%ROWCOUNT || ' row.');
END;
21
Invoking Procedures
• You can invoke (execute) a procedure from:
– An anonymous block
– Another procedure
– A calling application
• Note: You cannot invoke a procedure from inside a
SQL statement such as SELECT.
22
Invoking the Procedure from
Application Express
• To invoke (execute) a procedure in Oracle
Application Express, write and run a small
anonymous block that invokes the procedure.
• For example:
BEGIN
add_dept; END;
23
Correcting Errors in
CREATE PROCEDURE Statements
• If compilation errors exist, Application Express
displays them in the output portion of the SQL
Commands window.
• You must edit the source code to make corrections.
• When a subprogram is CREATED, the source code is
stored in the database even if compilation
errors occurred.
24
Correcting Errors in
CREATE PROCEDURE Statements
• After you have corrected the error in the code, you
need to recreate the procedure.
• There are two ways to do this:
– Use a CREATE OR REPLACE PROCEDURE statement to
overwrite the existing code (most common).
– DROP the procedure first and then execute the CREATE
PROCEDURE statement (less common).
25
Saving Your Work
• Once a procedure has been created successfully, you
should save its definition in case you need to modify
the code later.
26
Local Subprograms
• When one procedure invokes another procedure,
we would normally create them separately, but we
can create them together as a single procedure if we
like.
CREATE OR REPLACE PROCEDURE subproc
...
END subproc;
27
Local Subprograms
• All the code is now in one place, and is easier to read and
maintain.
• The nested subprogram's scope is limited to the
procedure within which it is defined; SUBPROC can be
invoked from MAINPROC, but from nowhere else.
CREATE OR REPLACE PROCEDURE mainproc
...
IS
PROCEDURE subproc (...) IS BEGIN
...
END subproc; BEGIN
...
subproc(...);
...
END mainproc;
30
28
Local Subprograms
• Every time an employee is deleted, we need to insert
a row into a logging table.
• The nested procedure LOG_EMP is called a Local
Subprogram.
CREATE OR REPLACE PROCEDURE delete_emp
(p_emp_id IN employees.employee_id%TYPE)
IS
PROCEDURE log_emp (p_emp IN employees.employee_id%TYPE) IS
BEGIN
INSERT INTO logging_table VALUES(p_emp, ...); END log_emp;
BEGIN
DELETE FROM employees
WHERE employee_id = p_emp_id; log_emp(p_emp_id);
END delete_emp;
29
Reference
PL/SQL User's Guide and Reference, Release 9.0.1
Part No. A89856-01
Copyright © 1996, 2001, Oracle Corporation. All rights
reserved.
Primary Authors: Tom Portfolio, John Russell
Oracle Academy
PLSQL S8L1 Creating Procedures
Copyright © 2019, Oracle and/or its affiliates. All rights reserved.
30