You are on page 1of 27

Unit 5:Understanding

Advance PL/SQL
By,
Asmatullah Khan,
CL/CP, GIOE,
Secunderabad.
Outline
1. Explain cursor attributes and cursor management
2. Explain database triggers
3. Explain the concept of stored sub programs with
examples
4. List atleast five advantages of packages.
5. Explain the specifications of packaging.
6. Explain overloading and calling packaged sub
programs.
PL/SQL Cursor – pointer to a context area
• Oracle creates a memory area, known as
context area(A cursor is a pointer to this
Attribute Description
context area), for processing an SQL
statement, which contains all information Returns TRUE if an INSERT, UPDATE, or
needed for processing the statement, for DELETE statement affected one or more
example, number of rows processed, etc. %FOUND rows or a SELECT INTO statement
returned one or more rows. Otherwise, it
• PL/SQL controls the context area through returns FALSE.
a cursor.
The logical opposite of %FOUND. It
• A cursor holds the rows (one or more) returns TRUE if an INSERT, UPDATE, or
returned by a SQL statement. The set of %NOTFOUND DELETE statement affected no rows, or a
rows the cursor holds is referred to as SELECT INTO statement returned no
the active set. rows. Otherwise, it returns FALSE.

• You can name a cursor so that it could be Always returns FALSE for implicit
referred to in a program to fetch and cursors, because Oracle closes the SQL
process the rows returned by the SQL %ISOPEN
cursor automatically after executing its
statement, one at a time.
associated SQL statement.

• There are two types of cursors:


▫ Implicit cursors Returns the number of rows affected by an
▫ Explicit cursors %ROWCOUNT INSERT, UPDATE, or DELETE statement,
or returned by a SELECT INTO statement.
Implicit cursors
• Implicit cursors are automatically created by Oracle whenever an
SQL statement is executed, when there is no explicit cursor for the
statement.
▫ Programmers cannot control the implicit cursors and the information in it.

• Whenever a DML statement (INSERT, UPDATE and DELETE) is


issued, an implicit cursor is associated with this statement.
▫ For INSERT operations, the cursor holds the data that needs to be
inserted.
▫ For UPDATE and DELETE operations, the cursor identifies the rows that
would be affected.

• In PL/SQL, you can refer to the most recent implicit cursor as


the SQL cursor (“SQL” is name of implicit cursor), which always has
the attributes like
▫ %FOUND,
▫ %ISOPEN,
▫ %NOTFOUND, and
▫ %ROWCOUNT.
Implicit Cursor attribute usage example
Explicit cursors
• Explicit cursors are programmer defined cursors for gaining more control over
the context area.

• An explicit cursor should be defined in the declaration section of the PL/SQL Block.

• It is created on a SELECT Statement which returns more than one row.

• Working with an explicit cursor involves four steps:


1. Declaring the cursor for initializing in the memory

2. Opening the cursor for allocating memory

3. Fetching the cursor for retrieving data

4. Closing the cursor to release allocated memory


Explicit Cursor Example
The oracle engine allows the user to define the procedures(called as triggers) that are
executed by oracle engine itself when an insert, update or delete statement is issued
against a table.

The triggers are executed procedures that are fired implicitly (internally) by the oracle
engine and not explicitly by the user.
PL/SQL Triggers Benefits of Triggers
• Triggers are stored programs, which are •Generating some derived
automatically executed or fired when column values automatically
some events occur; such in response to the
following events: •Enforcing referential
integrity
▫ A database manipulation (DML) statement •Event logging and storing
(DELETE, INSERT, or UPDATE). information on table access
•Auditing
▫ A database definition (DDL) statement
(CREATE, ALTER, or DROP). •Synchronous replication of
tables
▫ A database operation (SERVERERROR, •Imposing security
LOGON, LOGOFF, STARTUP, or
SHUTDOWN). authorizations
•Preventing invalid
• Triggers could be defined on the table, transactions
view, schema, or database with which the
event is associated.
Types of Triggers
1. BEFORE Trigger :
▫ BEFORE trigger execute before the
triggering DML statement (INSERT, • Combination Trigger : Combination
UPDATE, DELETE) execute. trigger are combination of two trigger
▫ Triggering SQL statement may or may not type,
execute, depending on the BEFORE trigger ▫ Before Statement Trigger :
conditions block.  Trigger fire only once for each
2. AFTER Trigger : statement before the triggering DML
▫ AFTER trigger execute after the triggering statement.
DML statement (INSERT, UPDATE, ▫ Before Row Trigger :
DELETE) executed.  Trigger fire for each and every record
▫ Triggering SQL statement is execute as before the triggering DML statement.
soon as followed by the code of trigger ▫ After Statement Trigger :
before performing Database operation.
 Trigger fire only once for each
• ROW Trigger : statement after the triggering DML
▫ ROW trigger fire for each and every record statement executing.
which are performing INSERT, UPDATE, ▫ After Row Trigger :
DELETE from the database table.  Trigger fire for each and every record
• Statement Trigger : after the triggering DML statement
▫ Statement trigger fire only once for each executing.
statement.
Syntax for Trigger Creation
• CREATE [OR REPLACE] TRIGGER trigger_name: Creates or
replaces an existing trigger with the trigger_name.

• {BEFORE | AFTER | INSTEAD OF}: This specifies when the


trigger would be executed. The INSTEAD OF clause is used for
creating trigger on a view.

• {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the


DML operation.

• [OF col_name]: This specifies the column name that would be


updated.

• [ON table_name]: This specifies the name of the table associated


with the trigger.

• [REFERENCING OLD AS o NEW AS n]: This allows you to refer


new and old values for various DML statements, like INSERT,
UPDATE, and DELETE.

• [FOR EACH ROW]: This specifies a row level trigger, i.e., the
trigger would be executed for each row being affected. Otherwise
the trigger will execute just once when the SQL statement is
executed, which is called a table level trigger.

• WHEN (condition): This provides a condition for rows for which


the trigger would fire. This clause is valid only for row level
triggers.
PL/SQL Trigger Example
PL/SQL Triggers Example 2
• Create the 'product' table and 'product_price_history'
table

CREATE TABLE product_price_history


(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );

CREATE TABLE product


(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );
PL/SQL Triggers Example 2 cont…
CREATE or REPLACE TRIGGER price_history_trigger
BEFORE UPDATE OF unit_price
ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history
VALUES
(:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price);
END;
/
UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100;
PL/SQL Trigger Example 3
CREATE TABLE product(Message varchar2(50), Current_Date number(32));

BEFORE UPDATE, Statement Level BEFORE UPDATE, Row Level


• This trigger will insert a record • This trigger will insert a record into
into the table 'product_check' the table 'product_check' before
before a sql update statement is each row is updated.
executed, at the statement level.
CREATE or REPLACE TRIGGER
CREATE or REPLACE TRIGGER Before_Upddate_Row_product
Before_Update_Stat_product BEFORE
BEFORE UPDATE ON product
UPDATE ON product FOR EACH ROW
Begin BEGIN
INSERT INTO product_check INSERT INTO product_check
Values('Before update, statement Values('Before update row level’,
level’, sysdate); sysdate);
END; END;
/ /
PL/SQL Trigger Example 3 cont…
CREATE TABLE product(Message varchar2(50), Current_Date number(32));

AFTER UPDATE, Statement Level AFTER UPDATE, Row Level


• This trigger will insert a record • This trigger will insert a record into
into the table 'product_check' the table 'product_check' after each
after a sql update statement is row is updated.
executed, at the statement level.
CREATE or REPLACE TRIGGER
CREATE or REPLACE TRIGGER After_Update_Row_product
After_Update_Stat_product AFTER
AFTER INSERT ON product
UPDATE ON product FOR EACH ROW
BEGIN BEGIN
INSERT INTO product_check INSERT INTO product_check
Values('After update, statement Values('After update, Row
level', sysdate); level',sysdate);
END; END;
/ /
Testing Trigger
• Now lets execute a update statement on table product.
UPDATE PRODUCT SET unit_price = 800 WHERE product_id in (100,101);
• Lets check the data in 'product_check' table to see the order in which the
trigger is fired.
SELECT * FROM product_check;

Output:

Mesage Current_Date
------------------------------------------------------------

Before update, statement level 26-Nov-2008


Before update, row level 26-Nov-2008
After update, Row level 26-Nov-2008
Before update, row level 26-Nov-2008
After update, Row level 26-Nov-2008
After update, statement level 26-Nov-2008
PL/SQL packages are schema objects that groups logically
related PL/SQL types, variables and subprograms.
PL/SQL Packages PL/SQL Package Advantages
•Package are reliable to granting a
privileges.
• A package is a collection of PL /SQL
elements that are "packaged" or
grouped together within a special •All function and procedure within a
BEGIN-END syntax, a kind of package can share variable among them.
"meta-block" of code.
•Package support overloading to overload
functions and procedures.
• Here is a partial list of the kinds of
elements you can place in a
package: •Package improve the
1. Cursors performance to loading the
2. Variables (scalars, records, tables, multiple object into memory at
etc.) and constants once, therefore, subsequent calls to
3. Exception names and PRAGMAs related program doesn't required to
for associating an error number calling physically I/O.
with an exception
4. PL /SQL table and record TYPE •Package reduce database connectivity
statements traffic as the PL/SQL block executes all at
5. Procedures and functions once.
Package Specification
• Package specification is the interface to the package.

• It just DECLARES the types, variables, constants, exceptions, cursors,


and subprograms that can be referenced from outside the package.
▫ In other words, it contains all information about the content of the
package, but excludes the code for the subprograms.

• All objects placed in the specification are called public objects. Any


subprogram not in the package specification but coded in the package
body is called a private object.
Package Body
• The package body has the codes for various methods declared in
the package specification and other private declarations, which
are hidden from code outside the package.

• The CREATE PACKAGE BODY Statement is used for creating the


package body.
Using the Package Elements
• The package elements (variables, procedures or
functions) are accessed with the following syntax:
PL/SQL Packages Example 2
Built-in PL/SQL Packages

You might also like