Download Triggers - Advanced Database System - Lecture Slides and more Slides Database Management Systems (DBMS) in PDF only on Docsity!
Event-Condition-Action (ECA)
• E vent occurs in databases
- addition of new row, deletion of row by DBMS
• C onditions are checked
• A ctions are executed if conditions are satisfied
- SQL + procedures
- All data actions performed by the trigger execute within
the same transaction in which the trigger fires,
- Cannot contain transaction control statements (COMMIT,
SAVEPOINT, ROLLBACK)
Types of SQL Triggers
- How many times should the trigger body execute when the
triggering event takes place?
- Per statement: the trigger body executes once for the
triggering event. This is the default.
- For each row: the trigger body executes once for each
row affected by the triggering event.
- When the trigger can be fired
- Relative to the execution of an SQL DML statement
(before or after or instead of it)
- Exactly in a situation depending on specific system
resources (e.g. signal from system clock)
Statement and Row Triggers
5
SQL> INSERT INTO dept (deptno, dname, loc) 2 VALUES (50, 'EDUCATION', 'NEW YORK');
Example 1: Monitoring Statement Events
SQL> UPDATE emp 2 SET sal = sal * 1. 3 WHERE deptno = 30;
Example 2: Monitoring Row Events
Execute for each row of table affected by event
Execute only once even if multiple rows affected
Example: Logging Operations
SQL> CREATE TRIGGER increase_salary_trg
2 BEFORE UPDATE OF sal
3 ON emp
4 BEGIN
5 INSERT INTO sal_hist(increased, changedOn)
6 VALUES (‘YES’, SYSDATE);
7 END;
9
Trigger name: increase_salary_trg Timing: BEFORE executing the statement Triggering event: UPDATE of sal column Target: emp table Trigger action: INSERT values INTO sal_hist table
Example: Calculating Derived Columns
11
SQL>CREATE OR REPLACE TRIGGER derive_commission_trg 2 BEFORE UPDATE OF sal ON emp 3 FOR EACH ROW 4 WHEN (new.job = 'SALESMAN') 5 BEGIN 6 :new.comm := :old.comm * (:new.sal/:old.sal); 7 END; 8 /
Trigger name: derive_commission_trg Timing: BEFORE executing the statement Triggering event: UPDATE of sal column Filtering condition: job = ‘SALESMAN’ Target: emp table Trigger parameters: old, new Trigger action: calculate the new commission
to be updated
Controlling Triggers using SQL
- Disable/Re-enable database trigger
- Disable or Re-enable all triggers for table
- Removing a trigger from database
13
ALTER TRIGGER trigger_name DISABLE | ENABLE
ALTER TABLE table_name DISABLE | ENABLE ALL TRIGGERS
DROP TRIGGER trigger_name
Using Database Triggers
- Auditing Table Operations
- each time a table is accessed auditing information is recorded against it
- Tracking Record Value Changes
- each time a record value is changed the previous value is recorded
- Protecting Database Referential Integrity: if foreign key points
to changing records
- referential integrity must be maintained
- Maintenance of Semantic Integrity
- e.g. when the factory is closed, all employees should become unemployed
- Storing Derived Data
- e.g. the number of items in the trolley should correspond to the current session selection
- Security Access Control
- e.g. checking user privileges when accessing sensitive information
Example: Counting Statement Execution
16
Whenever an employee record is deleted from database,
counter in an audit table registering the number of deleted rows
for current user in system variable USER is incremented.
SQL>CREATE OR REPLACE TRIGGER audit_emp
2 AFTER DELETE ON emp
3 FOR EACH ROW
4 BEGIN
5 UPDATE audit_table SET del = del + 1
6 WHERE user_name = USER
7 AND table_name = 'EMP’;
7 END;
Example: Tracing Record Value Changes
17
USER_NAME
EGRAVINA
NGREENBE
TIMESTAMP
12-SEP-
10-AUG-
ID
OLD_LAST_NAME
NULL
MAGEE
NEW_LAST_NAME
HUTTON
TURNER
OLD_TITL
E
NULL
CLERK
NEW_TITLE
ANALYST
SALESMAN
NEW_SALARY
… continuation
OLD_SALARY
NULL
Example: Protecting Referential Integrity
SQL>CREATE OR REPLACE TRIGGER
cascade_updates
2 AFTER UPDATE OF deptno ON dept
3 FOR EACH ROW
4 BEGIN
5 UPDATE emp
6 SET emp.deptno = :new.deptno
7 WHERE emp.deptno = :old.deptno;
8 END
19
Whenever the department number changes, all employee records
for this department will automatically be changed as well, so that
the employees will continue to work for the same department.
Restrictions for Database Triggers
- Problem: impossible to determine certain values during
execution of a sequence of operations belonging to one and
the same transaction
- Mutating tables: contain rows which change their values after
certain operation and which are used again before the current
transaction commits
- Preventing table mutation:
- Should not contain rows which are constrained by rows
from other changing tables
- Should not contain rows which are updated and read in
one and the same operation
- Should not contain rows which are updated and read via
other operations during the same transaction
Example: Mutating Table (fixed)
22
SQL> CREATE OR REPLACE TRIGGER emp_count 2 AFTER DELETE ON emp 3 -- FOR EACH ROW 4 DECLARE 5 num INTEGER; 6 BEGIN 7 SELECT COUNT(*) INTO num FROM emp; 8 DBMS_OUTPUT.PUT_LINE(' There are now ' || num || ' employees.'); 9 END; 10 /
SQL> DELETE FROM emp WHERE deptno = 30;
There are now 8 employees.
6 rows deleted.
Now the trigger becomes a statement trigger and the EMP table is no longer mutating.
Rules for Good SQL Practice
- Rule 1: Do not change data in the primary key,
foreign key, or unique key columns of any table
- Rule 2: Do not update records in the same table
you read during the same transaction
- Rule 3: Do not aggregate over the same table you
are updating
- Rule 4: Do not read data from a table which is
updated during the same transaction