Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 34

9/13/2007 9:13:55 AM PLSQL Training CSC India Pvt Ltd 1

PL/SQL Training
(Database Triggers)
Srinivas Nagula
snagula@csc.com
18-JUL-2011
To
22-JUL-2011
PL/SQL Training
9/4/20149/4/2014 5:41:44 AM 2
Database Triggers
What is a Trigger
Triggers are named PLSQL blocks with declarative, executable and exception-
handling sections, similar to procedures and functions
Triggers are stored as stand alone objects in database, cannot be local to a
block or package
Triggers are executed implicitly whenever the triggering event occurs, and
does not accepts arguments
PL/SQL Training
9/4/20149/4/2014 5:41:44 AM 3
Why Triggers?
Maintaining complex integrity constraints not possible through declarative
constraints enabled at table creation
Auditing information in a table by recording the changes made and who made
them
Automatically signaling other programs that action needs to take place when
changes are made to a table
Publishing information about various events in a publish subscribe
environment
PL/SQL Training
9/4/20149/4/2014 5:41:44 AM 4
Database Events

Table

Update
Trigger
Insert
Trigger
Update
Trigger
Update

Insert

Delete
DATABASE
User A User A LOGGING IN LOGGING OUT
Database Up
Database DOWN
Errors
User B
LOGGING IN
User B
LOGGING OUT
PL/SQL Training
9/4/20149/4/2014 5:41:44 AM 5
Trigger Types
DML Triggers
DML Trigger is fired by a DML statement, and the type of statement determines the type
of DML Trigger
DML Triggers are classified based on
Level --Row Level (fires for each row) /Statement Level
Timing --Before /After
Statement --Insert /Update/ Delete
Total --2X2X3=12 Types of DML Triggers
Instead of Triggers
Instead of Triggers are defined on views ONLY
Unlike DM Trigger which executes in addition to the DML operation, an Instead of Trigger
will execute instead of the DML statement that fired it
These should be ROW LEVEL ONLY
System triggers
System Trigger fires when a system event, such as STARTUP/SHUTDOWN occurs
System Trigger will be fired on DDL operations

PL/SQL Training
9/4/20149/4/2014 5:41:44 AM 6
Trigger Syntax
Syntax:
CREATE [OR REPLACE] TRIGGER trigger_name
{ BEFORE / AFTER/INSTEAD OF} trigger_event
referencing_clause
[FOR EACH ROW]
[WHEN trigger_condition]
trigger_body
trigger_name :is the name of trigger to be created
trigger_event :specifies the event that fires the
trigger
referencing_clause :is used to refer to the data in the row
currently being modified with a different name
trigger_condition :if present will be evaluated first.
trigger_body will be executed only when
trigger_condition is
evaluates to TRUE
trigger_body :The business logic to be executed
Note: The trigger body cannot exceed 32K
PL/SQL Training
9/4/20149/4/2014 5:41:44 AM 7
Trigger Example
create or replace trigger bfrupdEMPTRI
before update on EMPTRI
BEGIN
insert into TRI_TST values(SRITST.NEXTVAL, SYS.LOGIN_USER, sysdate);
END;
PL/SQL Training
9/4/20149/4/2014 5:41:44 AM 8
Creating DML Triggers
Category Values Description
Statement INSERT/UPDATE/
DELETE
Defines which kind of DML Statement causes
the trigger to fire
Timing Before /After Defines whether the trigger fires before are
After the statement is executed
Level Row / Statement If the trigger is row level, it fires once for each
row affected by the triggering statement
If the trigger is statement level, it fires once
either before or after the statement
A row level trigger is identified by the FOR
EACH ROW clause in trigger definition
A Table can have any number of triggers define on it, including more
than one of a given DML type
PL/SQL Training
9/4/20149/4/2014 5:41:44 AM 9
Row level Trigger Demo
create or replace trigger bfrupdEMPTRIr before update on EMPTRI
for each row
BEGIN
insert into TRI_TST values(SRITST.NEXTVAL, SYS.LOGIN_USER, sysdate);
END;
PL/SQL Training
9/4/20149/4/2014 5:41:44 AM
10
Order of DML Trigger Firing
Executes the Before Statement Triggers if present
For Each Row affected by the statement
Executes before Row level triggers if present
Execute the Statement (i.e trigger body)
Execute the After statement row level triggers if present
Executes the After Statement Level Triggers, if present
PL/SQL Training
9/4/20149/4/2014 5:41:44 AM 11
Correlation Identifiers (Row Level Triggers Only)
A row level trigger fires once per row processed by the triggering statement.
Inside the trigger we can access the data in the row that is being currently being processes
This is done through two correlation identifiers :new, :old
A correlation identifier is a special kind of PL/SQL bind variable
PL/SQL compiler will treat them as records type
triggering_table%ROWTYPE
Thus, :new.field is valid only if field is a field in triggering table
Triggering
Statement
:old :new
INSERT Undefined All fields are NULL Values that will be inserted when the
statement is complete
UPDATE Original values for the row before
the update
New values that will be updated when the
statement is complete
DELETE Original Values before the row is
deleted
Undefined all fields are Null
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
12
Correlation Identifiers
create table TRI_NEWOLD (old varchar2(20), new varchar2(20))

create or replace trigger aftupdEMPTRI
after update on EMPTRI
for each row
BEGIN
insert into TRI_NEWOLD values(:old.ename, :new.ename);
END;

select empno, ename from emp where deptno=10;

update emptri set ename=ename||'new' where deptno=10;

select * from TRI_NEWOLD;
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
13
Correlation Identifiers Clause Demo Output
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
14
Trigger Clauses
Referencing Clause: This clause is used to specify a different name for :old and
:new.
WHEN Clause: Is valid for Row Level Triggers ONLY. If present the trigger body
will be executed only for those rows that meet the condition specified by the WHEN
Clause
Trigger Predicates:
INSERTING, UPDATING and DELETING:
Determines what operation is being done inside trigger
These are Boolean type
Predicate Behavior
INSERTING TRUE if the triggering statement is an INSERT; FALSE otherwise
UPDATING TRUE if the triggering statement is an UPDATE; FALSE otherwise
DELETING TRUE if the triggering statement is an DELETE; FALSE otherwise
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
15
Referencing Clause
truncate table TRI_NEWOLD;

create or replace trigger aftupdEMPTRI
after update on EMPTRI
referencing old as ABC new as XYZ
for each row
BEGIN
insert into TRI_NEWOLD values(:ABC.ename, :XYZ.ename);
END;

update EMPTRI set ename=ename||'X' where deptno=10;

select * from TRI_NEWOLD;
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
16
Referencing Clause
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
17
Trigger Predicates Demo
drop trigger aftupdEMPTRI;

create or replace trigger aftupdEMPTRI
after update on EMPTRI
for each row
BEGIN
IF INSERTING then
insert into TRI_NEWOLD(OLD) values('Insertion Oprn');
ELSIF UPDATING THEN
insert into TRI_NEWOLD(OLD) values('Update Oprn');
ELSE
insert into TRI_NEWOLD(OLD) values('Delete Oprn');
END IF;
END;

update EMPTRI set sal=3950 where empno=7369;

select * from TRI_NEWOLD;
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
18
Trigger Predicates Demo Output
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
19
WHEN Clause
Valid for ROW Level Triggers ONLY

drop trigger aftupdEMPTRI;

create or replace trigger aftupdEMPTRI
after update on EMPTRI
for each row
when (old.sal > 2000)
BEGIN
insert into TRI_NEWOLD values(:old.sal, :new.sal);
END;
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
20
Instead of Triggers
These triggers fire instead of a DML operation
These are defined only on Views
Instead of triggers used in two cases
To allow a view that would not otherwise not to be modifiable to be modified
To modify the columns of a nested table column in a view
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
21
Modifiable Vs Non-Modifiable Views
A modifiable view is one against which we can issue a DML statement
A view is modifiable if it does not contain any of the following
Set operators (UNION, UNION ALL, MINUS)
Aggregate functions (SUM, AVG, etc)
GROUP BY, CONNECT BY, START WITH clauses
The distinct operator
Joins
Exception: Some views with Joins also modifiable.
A Join View is modifiable if the DML operation on it modifies only one base table a time and
the DML statement meets the following conditions
INSERT: The statement does not refer, implicitly or explicitly, to the columns of a non-
key preserved table
Update: The updated columns map to key preserved table
Delete: There is exactly one key preserved table in the join
Key Preserved Table: A table is key preserved table if, after a join with another table,
the keys in the original table are also keys in the resultant join
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
22
System Triggers
System Triggers are two types
DDL Events includes CREATE, ALTER, DROP Statements
Database events includes STARTUP/SHUTDOWN of the server, logon/logoff os user and a
Server Error
Database Level events
Schema Level events
Syntax
CREATE [OR REPLACE] TRIGGER [schema.]trigger_name
{BEFORE/AFTER}
{ddl_event_list|database_event_list}
On {DATABASE|[schema.]SCHEMA}
[when_clause]
trigger_body;
ddl_event_list:Is one or more DDL events separated by OR key word
database_event_list:Is one or more database events separated by OR key word
Note: No Database Event for TRUNCATE
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
23
SCHEMA Level Trigger Example
Create Trigger Using SCHEMA Level Trigger
Log oof to User
Login to User again
Log of User
&
Login again
1
2
3
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
24
SCHEMA Level Trigger Example
Only SYS, SYSDBA Users can create DATABASE Level Triggers
Login AS SYSDBA
Create the trigger
Log off and Log IN
drop trigger LogonAft;
truncate table tabsys;
create or replace trigger
LogonAft
after LOGON ON DATABASE
BEGIN
insert into
scott.tabsys
values(SYS.LOGIN_USER,
sysdate);
END;

PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
25
System Events
Event Timing Allowed Description
STARTUP AFTER Fired when an Instance is started up
SHUTDOWN BEFORE Fired when an Instance is shu down. This event
may not fire if the database is shutdown
abnormally
SERVERERROR AFTER Fired whenever an error occurs
LOGON AFTER Fired after a user has successfully connected to
the database
LOGOFF BEFORE Fired at the start of logoff
CREATE BEFORE/AFTER Fired before or after a schema object is created
DROP BEFORE/AFTER Fired before or after a schema object is dropped
ALTER BEFORE/AFTER Fired before or after a schema object is altered
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
26
Database & Schema Trigger

A system trigger can be defined at the database level or a schema level
A database level trigger will fire whenever the triggering event occurs
A schema level trigger will fire only when the triggering event occurs for the
specified schema
DATABASE /SCHEMA keywords determine the level for a given system trigger
If schema is not specified with SCHEMA key word the it defaults to the schema that
owns the trigger
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
27
Event Attribute Functions
These functions allows the trigger body to get information about the triggering event
These functions are standalone PLSQL functions owned by SYS.
When we are accessing these functions we must prefix them with SYS.

PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
28
Event Attribute Functions
Attribute Function Datatype System Event
Applicable For
Description
SYSEVENT VARCHAR2 All Events Returns the system event fired the trigger
INSTANCE_NUM NUMBER All Events

Returns the current instance number
DATABASE_NAME VARCHAR2 All Events Returns the current Database name
IS_SERVERERROR BOOLEAN SERVERERROR Takes an error number as an argument, and returns TRUE if the Oracle
error indicated is on the error stack
SERVER_ERROR NUMBER SERVERERROR Takes a single Number argument. Returns the error at the position on
the error stack indicated by the argument. The position 1 is the top of the
stack
LOGIN_USER VARCHAR2 All events Returns the userid of the user that fired the trigger
DICTIONARY_OBJ_TYP
E
VARCHAR2 CREATE, DROP,
ALTER
Returns the type of dictionary object on which the DDL operation that
fired the trigger occurred
DICTIONARY_OBJ_NA
ME
VARCHAR2 CREATE, DROP,
ALTER
Returns the name of the dictionary object on which DDL operation that
fired the trigger occurred
DICTIONARY_OBJ_OW
NER
VARCHAR2 CREATE, DROP,
ALTER
Returns the owner of the dictionary object on which the DDL operation
that fired the trigger occurred
DES_ENCRYPTED_PAS
SWORD
VARCHAR2 CREATE or ALTER
USER
Returns the DES encrypted password of the user being created or
altered
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
29
System Triggers Restrictions on WHEN Clause
STARTUP and SHUTDOWN triggers cannot have any conditions
SERVERERROR triggers can use the ERRNO test to check for a specific error only
LOGON, LOGOFF triggers can check the user id or username with the USERID or
USERNAME test
DDL Triggers can check the type and name of the object being modified, and can check the
user id and user name

Trigger Names - - Namespace
The Name Space for triggers is different from subprograms
A Namespace is the set of legal identifiers available for use as names of an object.
Procedures, Functions, Tables uses share namespace. Triggers uses a different one.

PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
30
Dropping & Disabling Triggers
Dropping a Trigger
DROP TRIGGER <trigger_name>

Disabling Trigger
ALTER TRIGGER TRIGGER NAME {DISABLE|ENABLE}

To Disable/Enable All the Triggers on a Table
ALTER TABLE <TABLE NAME> ENABLE/DISABLE All TRIGGERS


PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
31
Restrictions on Triggers
Trigger should not issue any transaction control statements
COMMIT/ROLLBACK/SAVEPOINT/ SET TRANSACTION
PLSQL Compiler will allow these statements, but an error will be generated when trigger is
fired
Any procedures and functions that are called by the trigger body cannot issue transaction
control statements (Unless they are also declared as autonomous )
Trigger body cannot declare any LONG or LONG RAW variables.
:new, :old cannot refer to a LONG, LONG RAW columns in the table
Trigger body may reference and use LOB columns, but it will may not modify the values of
the columns
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
32
Trigger Privileges
System Privilege Description
CREATE TRIGGER Allows the grantee to create a trigger in his own schema
CREATE ANY
TRIGGER
Allows the grantee to create triggers in any schema except SYS. It is
not recommended to create triggers on data dictionary tables
ALTER ANY TRIGGER Allows the grantee to enable, disable or compile database triggers in
any schema
DROP ANY TRIGGER Allows the grantee to drop database triggers in any schema except
SYS
ADMISITER
DATABASE TRIGGER
Allows the grantee to create or alter a system trigger on the database.
The grantee must also have either CREATE TRIGGER or CREATE
ANY TRIGGER
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
33
Data Dictionary
Trigger source code will be stored in the Table USER_TRIGGERS
USER_TRIGGERS Table
SQL> desc USER_TRIGGERS;
---------------------------------------------------------------------------
Name Null? Type
---------------------------------------------------------------------------
TRIGGER_NAME VARCHAR2(30)
TRIGGER_TYPE VARCHAR2(16)
TRIGGERING_EVENT VARCHAR2(227)
TABLE_OWNER VARCHAR2(30)
BASE_OBJECT_TYPE VARCHAR2(16)
TABLE_NAME VARCHAR2(30)
COLUMN_NAME VARCHAR2(4000)
REFERENCING_NAMES VARCHAR2(128)
WHEN_CLAUSE VARCHAR2(4000)
STATUS VARCHAR2(8)
DESCRIPTION VARCHAR2(4000)
ACTION_TYPE VARCHAR2(11)
TRIGGER_BODY LONG
---------------------------------------------------------------------------
PL/SQL Training
9/4/20149/4/2014 5:41:45 AM
34
Srinivas Nagula
Subprograms

You might also like