29 Active Database
Dr R. Baskaran
Syntax for creating triggers in SQL
- Trigger name – unique within one database schema
- Timing – depends on the order of controlled events (before or after or instead of)
- Triggering event – event which fires the trigger (E)
- Filtering condition – checked when the triggering event occurs (C)
- Target – table (or view) against which the trigger is fired; they should be both created within the same schema
- Trigger Parameters – parameters used to denote the record columns; preceded by colon:new, :old for new and old versions of the values respectively
- Trigger action – SQL statements, executed when the trigger fires; surrounded by Begin … End (A)
CREATE [OR REPLACE] TRIGGER trigger_name
timing event1 [OR event2 OR event3] ON table_name
BEGIN
SQL statements;
END;
The trigger body consisting of SQL statements will be executed only once according to the prescribed timing, when the event1 (event2, event3) occurs against the monitored table in question table_name.
Syntax for Creating Row Triggers
CREATE [OR REPLACE] TRIGGER trigger_name
timing event1 [OR event2 OR event3] ON table_name
[REFERENCING OLD AS old | NEW AS new]
FOR EACH ROW
[WHEN condition]
BEGIN
SQL statements;
END
The trigger body consisting of SQL statements will be executed once for each row affected by event1 (event2, event3) in the table named table_name subject to the additional condition.
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 Execution Order
1. Execute all BEFORE STATEMENT triggers.
2. Disable temporarily all integrity constraints recorded against the table.
3. Loop for each row in the table.
- Execute all BEFORE ROW triggers.
- Execute the SQL statement against the row and perform integrity constraint checking of the data.
- Execute all AFTER ROW triggers.
4. Complete deferred integrity constraint checking against the table.
5. Execute all AFTER STATEMENT triggers.
Controlling Triggers using SQL
Disable/Re-enable database trigger
ALTER TRIGGER trigger_name DISABLE | ENABLE
Disable or Re-enable all triggers for table
ALTER TABLE table_name DISABLE | ENABLE ALL TRIGGERS
Removing a trigger from database
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
Counting Statement Execution
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;
8
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.
Recording Changes
SQL>CREATE OR REPLACE TRIGGER audit_emp_values 2 AFTER DELETE OR UPDATE ON emp
3 FOR EACH ROW
4 BEGIN
5 INSERT INTO audit_emp_values (user_name,
6 timestamp, id, old_last_name, new_last_name,
7 old_title, new_title, old_salary, new_salary)
8 VALUES (USER, SYSDATE, :old.empno, :old.ename,
9 :new.ename, :old.job, :new.job,
10 :old.sal, :new.sal);
11 END;
Whenever some details for an employee are deleted or updated, both the previous and new details are recorded in an audit table to allow tracing the history of changes. An insert operation cannot be recorded with this trigger as old.empno has no value.
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
9 /
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
Mutating Table
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
2 WHERE deptno = 30;
Under the bar is code entered in SQL-PLUS which triggers cascade_updates in this case. Triggers are not executed directly.
Mutating Table (fixed)
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.
SUMMARY
- Active DBMSs embed situation-action rules in database.
- Support many functionalities:
- E.g.: Integrity control,access control,monitoring,derived data,change notification.
- Some Active DBMS functionality commercially available in SQL:99 as triggers.