You are on page 1of 20

RDBMS Using Oracle

Creating Database Triggers

Kamran.Munir@niit.edu.pk

Triggers Overview

A trigger is a PL/SQL block that executes


whenever a particular event takes place.

In this lecture we will learn


z
z
z

Database triggers and their use


How to create database triggers
Triggers firing rules

Trigger Components
Triggering Event:

z
z
z
z

When DML operation will cause the trigger to


execute?
Insert
Update
Delete
Any combination of above

Trigger Components
Timing:

When should the trigger fire?

Before
The code will execute before the DML event

After
The code will execute after the DML event

Trigger Components contd..

Trigger Body:
z

What action should the trigger perform?

<Syntax>
[DECLARE]
BEGIN
[EXCEPTION]
END;

Trigger Components contd..


Trigger Type

How many times should the trigger body execute


when the triggering event takes place?
1- Statement [Default]
The trigger body executes once for the triggering
event.
2- Row
The trigger body executes once for each row
affected by the triggering event.

Lets see the difference Between

Statement & Row level trigger


With a general example

Statement & Row level trigger

SQL> Insert into dept


values(50, EDUCATION, NEW YORK);
Statement [Default]
The trigger body executes once for
the triggering event.

SQL> Update emp set sal = sal * 1.1;


2- Row
The trigger body executes once for each
row affected by the triggering event.

Creating Trigger

Syntax for creating Statement Trigger

CRAETE [OR REPLACE] TRIGGER triger_name


timing (Before or After) event (INSERT, DELETE, UPDATE)
on <table_name
>
<table_name>
PL/SQL Block;

Creating Statement Trigger


CREATE OR REPLACE TRIGGER SECURE_EMP
BEFORE INSERT ON EMP
BEGIN
IF
(TO_CHAR (SYSDATE, 'DY') IN ('SAT','SUN','TUE'))
THEN
RAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR(-20500, 'YOU CAN ONLY
INSERT DATA INTO EMP DURING WEDNESDAY TO
FRIDAY');
FRIDAY');
END IF;
END;
Output: trigger created

SQL> INSERT INTO EMP(EMPNO, DEPTNO)


VALUES(1234, 30);

* ERROR
ORAORA-20500: YOU CAN ONLY INSERT DATA INTO EMP
DURING WEDNESDAY TO FRIDAY

Example # 2

CREATE OR REPLACE TRIGGER SECURE_EMP


BEFORE INSERT OR UPDATE OR DELETE ON EMP
BEGIN
IF (TO_CHAR (SYSDATE, 'DY') IN ('SAT','SUN')) OR
(TO_CHAR (SYSDATE, 'HH24') NOT BETWEEN '08' AND 18)
THEN
IF DELETING THEN
RAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR(-20501, 'YOU CAN ONLY
DELETE DURING NORMAL OFFICE HOURS');
ELSIF INSERTING THEN
RAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR(-20507, 'YOU CAN ONLY
INSERT DATA INTO EMP DURING OFFICE HOURS');
ELSIF UPDATING ('SAL') THEN
RAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR(-20502, 'YOU CAN ONLY
UPADTE SALERY DURING OFFICE HOURS');
ELSE
RAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR(-20504, 'YOU CAN ONLY
UPADTE DURING OFFICE HOURS');
END IF;
END IF;
END;

SQL> INSERT INTO EMP(EMPNO, DEPTNO) VALUES(12345, 40);


INSERT INTO EMP(EMPNO, DEPTNO) VALUES(12345, 40)
*
ERROR at line 1:
ORAORA-20507: YOU CAN ONLY INSERT DATA INTO EMP DURING
OFFICE HOURS

SQL> UPDATE EMP


2 SET SAL = SAL * 10;
UPDATE EMP
*
ERROR at line 1:
ORAORA-20502: YOU CAN ONLY UPADTE SALERY DURING OFFICE
HOURS

SQL>
1 UPDATE EMP
2* SET EMPNO = 1245
UPDATE EMP
*
ERROR at line 1:
ORAORA-20504: YOU CAN ONLY UPADTE DURING OFFICE HOURS

Triggers contd
contd
Creating a Row Triggers

Kamran.Munir@niit.edu.pk

Review:

Trigger Components contd..

Trigger Type
How many times should the
trigger body execute when
the triggering event takes
place?

values(50, EDUCATION, NEW


YORK);
Statement [Default]
The trigger body executes once for
the triggering event.

1- Statement [Default]
The trigger body executes once
for the triggering event.
2- Row

SQL> Insert into dept

SQL> Update emp set sal = sal * 1.1;

2- Row
The trigger body executes
once for each row affected by The trigger body executes once for each
row affected by the triggering event.
the triggering event.

Creating Row Trigger

Syntax for creating ROW Trigger


CRAETE [OR REPLACE] TRIGGER triger_name
timing (Before or After) event (INSERT, DELETE, UPDATE)
on <table_name>
FOR EACH ROW
[WHEN condition]
PL/SQL Block;

This condition is
checked for each row

10

Problem
Create a row trigger to keep a
running count of DML
operations by different users
on a database table [EMP].
Username

Table name

C_Delete

C_Insert

C_Update

SCOTT
ALI
XYZ

EMP
EMP
EMP

4
0
0

5
1
3

4
9
1

Problem Solution
Here we will create a [AFTER TIMING] trigger as we want to
Keep track of all successful DML operations
And
We will use trigger FOR EACH ROW as we want to
count number of rows affected
by the DML statement (in case of Delete or update).

11

CREATE OR REPLACE TRIGGER DML_COUNT_EMP


AFTER INSERT OR UPDATE OR DELETE ON EMP
FOR EACH ROW
BEGIN
IF DELETING THEN
UPDATE DML_EMP set C_DELETE = C_DELETE + 1
Where USERNAME = user and tablename = EMP;
ELSIF INSERTING THEN
UPDATE DML_EMP set C_INSERT = C_INSERT + 1
Where USERNAME = user and tablename = EMP;
ELSIF UPDATING ('SAL') THEN
UPDATE DML_EMP set C_UPDATE = C_UPDATE + 1
Where USERNAME = user and tablename = EMP;
ELSE
UPDATE DML_EMP set C_UPDATE = C_UPDATE + 1
Where USERNAME = user and tablename = EMP;
END IF;
END;

SQL> insert into emp(empno,


emp(empno, deptno)
deptno) values(1, 10)

1 row created.

SQL> select * from dml_emp;


dml_emp;
USERNAME
TABLENAME
C_INSERT
-------------------- -------------------SCOTT
EMP
KAMRAN
EMP

C_DELETE C_UPDATE
--------- -------0
0

- --------0
1
0
0

12

SQL> update emp set deptno = 10;


15 rows updated.

SQL> select * from dml_emp;


dml_emp;
USERNAME
TABLENAME
C_INSERT
--------------- -------------------SCOTT
EMP
KAMRAN
EMP

C_DELETE C_UPDATE
--------0
0

--------15
0

--------1
0

Difference between
Triggers and Procedures

13

Difference between Triggers and Procedures

Triggers

Procedures

Use CREATE TRIGGER

Use CREATE PROCEDURE

Data Dictionary contains


source and pp-code

Data Dictionary contains


source and pp-code

COMMIT and ROLLBACK are COMMIT and ROLLBACK are


allowed.
not allowed.
Invoked Implicitly

Invoked Explicitly

OLD & NEW


In triggers we can also track users
activities performed against any table.
We can record the values both before
and after the data changes by using
OLD and NEW qualifiers with
respective column names.

14

Syntax for creating ROW Trigger


CRAETE [OR REPLACE] TRIGGER triger_name
timing (Before or After) event (INSERT, DELETE, UPDATE)
on <table_name>
[REFERENCING OLD AS old | NEW as new]
FOR EACH ROW
[WHEN condition]
This condition is
checked for each row
PL/SQL Block;

SQL> create table audit_emp_values


(user_name varchar(20),
timestamp date,
id number(10),
old_ename varchar2(20),
new_ename varchar2(20),
old_sal number(10),
new_sal number(10));
Table created.

SQL> desc AUDIT_EMP_VALUES;


Name
Null? Type
------------------------------- -------- ---USER_NAME
VARCHAR2(20)
TIMESTAMP
DATE
ID
NUMBER(10)
OLD_ENAME
VARCHAR2(20)
NEW_ENAME
VARCHAR2(20)
OLD_SAL
NUMBER(10)
NEW_SAL
NUMBER(10)
.
..

15

Using OLD and NEW

Now a trigger that will track users activities


performed against EMP table.

We will record the values both before and after the


data changes.

CREATE OR REPLACE TRIGGER audit_emp_values


After DELETE OR INSERT OR UPDATE on emp
FOR EACH ROW
BEGIN
Insert into audit_emp_values (user_name, timestamp, id,
old_ename,new_ename, old_sal, new_sal)
Values (user,sysdate, :old.empno, :old.ename,
:new.ename, :old.sal,:new.sal);
END;

16

INSERT
SQL> insert into emp(empno, ename, sal)

values(1111, 'TEST', 5000);


SQL> select USER_NAME, TIMESTAMP , NEW_ENAME, NEW_SAL
from Audit_emp_values;
Audit_emp_values;
USER_NAME TIMESTAMP NEW_ENAME
---------------- ------------------------------SCOTT
10TEST
10-DECDEC-04

NEW_SAL
--------5000

UPDATE
SQL> update emp
2 set sal = 6000
3 where empno = 1111;
1 row updated.
SQL> select * from audit_emp_values;
audit_emp_values;
USER_NAME TIMESTAMP ID OLD_ENAME NEW_ENAME OLD_SAL NEW_SAL
-------------------- ----------------- -------------------- -------------------- --------- --------SCOTT
10TEST
5000
10-DECDEC-04
SCOTT
10TEST
5000
6000
10-DECDEC-04 1111 TEST

17

DELETE
SQL> delete from emp where ename = 'TEST';
1 row deleted.

USER_NAME
TIMESTAMP
ID
---------------- ----------------SCOTT
10-DEC-04
SCOTT
10-DEC-04 1111
SCOTT
10-DEC-04 1111

OLD_ENAME NEW_ENAME OLD_SAL NEW_SAL


-------------------- -------------------- --------- --------TEST
5000
TEST
TEST
5000
6000
TEST
6000

Think what else we can do


with triggers

Give suggestions.

18

Managing Triggers

To Enable or Disable a Trigger

Alter Trigger <trigger_name> DISABLE | ENABLE;

To Enable or Disable all Trigger on a Table

Alter TABLE <TABLE NAME> DISABLE | ENABLE All


TRIGGERS;

Recompile a trigger for a table

Alter trigger <trigger_name> COMPILE;

Removing Trigger

DROP TRIGGER <trigger<trigger-name>;

19

Q
&

Thanks

20

You might also like