ISYS 365 Triggers 1 Agenda n Triggers n

  • Slides: 24
Download presentation
ISYS 365 Triggers 1

ISYS 365 Triggers 1

Agenda n Triggers n n n n Review Correlation identifiers (pseudo records) Restrictions on

Agenda n Triggers n n n n Review Correlation identifiers (pseudo records) Restrictions on triggers Trigger usage Mutating tables Enabling and disabling triggers Data Dictionary 2

Triggers: Syntax CREATE OR REPLACE TRIGGER trigger_Name {BEFORE|AFTER} {INSERT|UPDATE| DELETE} [OF column_name] ON table_name

Triggers: Syntax CREATE OR REPLACE TRIGGER trigger_Name {BEFORE|AFTER} {INSERT|UPDATE| DELETE} [OF column_name] ON table_name [FOR EACH ROW] [WHEN trigger_condition] DECLARE -- variable declaration goes here BEGIN IF INSERTING THEN -- statements here ELSIF UPDATING THEN -- statements here ELSIF DELETING THEN -- statements here END IF; END [trigger_Name]; 3

Recommended Naming Convention n Table_Name_[A|B][I|U|D][S|R] n n [A|B] AFTER or BEFORE [I|U|D] INSERT, UPDATE,

Recommended Naming Convention n Table_Name_[A|B][I|U|D][S|R] n n [A|B] AFTER or BEFORE [I|U|D] INSERT, UPDATE, DELETE [S|R] statement-level or row-level Example: n n n Employee_AIUS Employee_BUR Department_BIUDR 4

Triggers: Correlation Identifiers n Correlation identifiers n n Row-level triggers can access individual column

Triggers: Correlation Identifiers n Correlation identifiers n n Row-level triggers can access individual column values : old and : new (called pseudo records) Syntactically treated as records of type triggering_table%ROWTYPE Reference fields within the pseudorecords using dot notation (just like implicit records) n : old. salary : new. salary 5

Triggers: Correlation Identifiers n : old. column_name n n n Contains the value prior

Triggers: Correlation Identifiers n : old. column_name n n n Contains the value prior to the change NULL for INSERT statements : new. column_name n n Contains the value after the change NULL for DELETE statements 6

Triggers: Correlation Identifiers n Testing : old value against : new value n will

Triggers: Correlation Identifiers n Testing : old value against : new value n will only work for UPDATE statement : old. salary <> : new. salary n n INSERT has only : new value DELETE has only : old value 7

Example of correlation identifiers /* Log any changes to employee salary where the increase

Example of correlation identifiers /* Log any changes to employee salary where the increase is greater than 10% */ CREATE OR REPLACE TRIGGER employee_BUR BEFORE UPDATE ON employee FOR EACH ROW WHEN (NEW. amount/OLD. amount > 1. 1) BEGIN INSERT INTO Employee_Big_Change VALUES (: NEW. action. Date, : OLD. sal, : NEW. sal); END employee_BUR; 8

Triggers: Correlation Identifiers Approach 1 Approach 2 CREATE OR REPLACE TRIGGER employee_BUR BEFORE UPDATE

Triggers: Correlation Identifiers Approach 1 Approach 2 CREATE OR REPLACE TRIGGER employee_BUR BEFORE UPDATE OF SALARY ON EMPLOYEE CREATE OR REPLACE TRIGGER employee_BUR FOR EACH ROW BEFORE UPDATE OF SALARY ON WHEN (OLD. SALARY <> NEW. SALARY) EMPLOYEE DECLARE FOR EACH ROW v_Sal_Difference NUMBER; DECLARE BEGIN v_Sal_Difference NUMBER; -- do something here BEGIN END employee_BUR; IF : old. salary <> : new. salary THEN / -- do something here NOTE: When using Approach 2, do NOT include END IF; the colons before the words OLD and NEW in the WHEN clause. END employee_BUR; / 9

Restrictions on Triggers n n Cannot have any transaction control statements (e. g. COMMIT,

Restrictions on Triggers n n Cannot have any transaction control statements (e. g. COMMIT, ROLLBACK or SAVEPOINT) Cannot call procedures or functions that issue any transaction control statements Cannot declare any LONG or LONG RAW variables : new and : old cannot refer to LONG or LONG RAW column 10

Trigger Usage: Summary data: use a statement-level trigger CREATE OR REPLACE TRIGGER patient_AIDUS AFTER

Trigger Usage: Summary data: use a statement-level trigger CREATE OR REPLACE TRIGGER patient_AIDUS AFTER INSERT OR DELETE OR UPDATE ON patient DECLARE CURSOR c_stat IS SELECT doctor_ID, COUNT(*) total_patients FROM patient GROUP BY doctor_ID; BEGIN FOR v_Stat. Rec IN c_stat LOOP UPDATE doctor_stats SET total_patients = v_Stat. Rec. total_patients WHERE Doctor_ID = v_Stat. Rec. Doctor_ID; IF SQL%NOTFOUND THEN INSERT INTO doctor_stats VALUES(v_Stat. Rec. Doctor_ID, v_Stat. Rec. total_patients); END IF; END LOOP; END patient_AIDUS; / Another example would be in an order processing system…. define the trigger on the order. Detail table to 11 update the total on the Order. Header table.

Trigger Usage: Overriding the values supplied in an INSERT/UPDATE statement by changing the :

Trigger Usage: Overriding the values supplied in an INSERT/UPDATE statement by changing the : new correlation value n Use BEFORE INSERT or BEFORE UPDATE rowlevel trigger CREATE OR REPLACE TRIGGER patient_BIR BEFORE INSERT ON PATIENT FOR EACH ROW BEGIN SELECT sequence_patient. ID. NEXTVAL INTO : new. patient. ID FROM DUAL; END patient_BIR; / INSERT INTO patient (Fname, lname) VALUES (‘Bob’, ‘Smith’); CREATE SEQUENCE_PATIENTID INCREMENT BY 1 START WITH 1; /* Note that Patient ID is automatically generated by the trigger. */ 12

Trigger Usage n Auditing: Use AFTER Row-level trigger 13

Trigger Usage n Auditing: Use AFTER Row-level trigger 13

Auditing Example CREATE OR REPLACE TRIGGER CALC_DOCTOR_STATS_AUIDS AFTER INSERT OR UPDATE OR DELETE ON

Auditing Example CREATE OR REPLACE TRIGGER CALC_DOCTOR_STATS_AUIDS AFTER INSERT OR UPDATE OR DELETE ON PATIENT DECLARE v_Dname VARCHAR 2(30); v_Tot_Patients NUMBER; CURSOR C_DOCTOR_STATS IS SELECT PHY_LNAME, COUNT(SSN) FROM PATIENT, PHYSICIAN WHERE PHY_ID = PRIMARY_PHY_ID GROUP BY PHY_LNAME; BEGIN DELETE FROM DOCTOR_STATS; -- wipe doctor_stats records OPEN c_DOCTOR_STATS; LOOP -- walk through cursor FETCH c_DOCTOR_STATS INTO v_Dname, v_tot_patients; EXIT WHEN c_DOCTOR_STATS%NOTFOUND; -- create new doctor stat record for each doctor INSERT INTO DOCTOR_STATS VALUES(v_Dname, v_Tot_Patients); END LOOP; END CALC_DOCTOR_STATS_AUIDS; 14

Using Raise Application Error in Triggers CREATE OR REPLACE TRIGGER patient_bds BEFORE DELETE ON

Using Raise Application Error in Triggers CREATE OR REPLACE TRIGGER patient_bds BEFORE DELETE ON patient DECLARE e_weekend_error EXCEPTION; e_not_supervisor EXCEPTION; BEGIN IF TO_CHAR(SYSDATE, 'DY') = 'SAT' OR TO_CHAR(SYSDATE, 'DY') = 'SUN' THEN RAISE e_weekend_error; END IF; IF SUBSTR(user, 1, 3) <> 'SUP' THEN RAISE e_not_supervisor; END IF; EXCEPTION WHEN e_weekend_error THEN RAISE_APPLICATION_ERROR (-20001, 'Deletions allowed Mon thru Fri only'); WHEN e_not_supervisor THEN -- INSERT INTO SECURITY_VIOLATIONS VALUES(USER, SYSDATE); RAISE_APPLICATION_ERROR (-20002, 'You '||user||' are not authorised to perform deletions'); END; / 15

Exercise n (1) (2) Suppose we have a Worker table as follows: worker(worker. ID,

Exercise n (1) (2) Suppose we have a Worker table as follows: worker(worker. ID, lname, gender, salary, commission, dept. ID) Declare a sequence for worker. ID that begins from 1. Write a trigger that automatically inserts the primary key with a sequential number when inserting a record in the worker table. 16

Exercise Trigger: n Suppose we have the following two tables: Order. Header(Order. ID, Odate,

Exercise Trigger: n Suppose we have the following two tables: Order. Header(Order. ID, Odate, Cust. ID, Total) Order_Item(Order. ID, Item. ID, Qty, Subtotal) n Write a statement-level trigger that updates the Total in the order. Header table with the total value of the order_item records whenever an insert, update or delete event occurs on the order_item table. For any update error, raise an exception. 17

Enabling & Disabling Triggers n n n ALTER TRIGGER trigger_name {ENABLE | DISABLE} Ex:

Enabling & Disabling Triggers n n n ALTER TRIGGER trigger_name {ENABLE | DISABLE} Ex: ALTER TRIGGER Employee_BIUR DISABLE; ALTER TABLE table_name {ENABLE | DISABLE} ALL TRIGGERS; Ex: ALTER TABLE emp ENABLE ALL TRIGGERS; DROP TRIGGER trigger_name; Ex: DROP TRIGGER Employee_BIUR; 18

Example - In order to disable, substitute DISABLE for ENABLE - By default, all

Example - In order to disable, substitute DISABLE for ENABLE - By default, all triggers are enabled when they are created - When a trigger is disabled, it still exists in the DD but is never fired - The STATUS column of USER_TRIGGERS contain either DISABLED or ENABLED value 19

Dropping Triggers n n Dropping Triggers DROP TRIGGER emp_bur; Trigger Dependencies - When a

Dropping Triggers n n Dropping Triggers DROP TRIGGER emp_bur; Trigger Dependencies - When a table is dropped, all triggers for that table are deleted from the DD ( When a table is dropped, all packages are disabled) 20

Data Dictionary n user_triggers view n n n trigger_type, table_name, triggering_event, status To list

Data Dictionary n user_triggers view n n n trigger_type, table_name, triggering_event, status To list all of the triggers that you have created: SELECT trigger_type, table_name, triggering_event, status FROM user_triggers; Other views that list triggers n n all_triggers list triggers that are accessible to current user (but might be owned by a different user) dba_triggers list all triggers in the database 21

USER_TRIGGERS SQL> select trigger_name, trigger_type, status from user_triggers; TRIGGER_NAME TRIGGER_TYPE STATUS --------------- -------LOGEMPCHANGE AFTER

USER_TRIGGERS SQL> select trigger_name, trigger_type, status from user_triggers; TRIGGER_NAME TRIGGER_TYPE STATUS --------------- -------LOGEMPCHANGE AFTER EACH ROW ENABLED SQL> select trigger_name, table_name from user_triggers; TRIGGER_NAME TABLE_NAME ---------------LOGEMPCHANGE EMPLOYEE SQL> select description from user_triggers; DESCRIPTION ----------------------------------------Log. Emp. Change AFTER INSERT OR DELETE OR UPDATE ON Employee FOR EACH ROW 22

Mutating Tables n A table is mutating when n n It is being modified

Mutating Tables n A table is mutating when n n It is being modified by a DML statement (the table on which the trigger is defined) It is being updated to enforce DELETE CASCADE constraints It is being read to enforce referential integrity (RI) constraints Constraining table n A table that may need to be read from for RI 23

Mutating Tables n SQL statements in Row-level trigger may NOT n n n Restrictions

Mutating Tables n SQL statements in Row-level trigger may NOT n n n Restrictions above apply to: n n n Read from or modify any mutating table Read from or modify the PK, UNIQUE or FK of a constraining table. They can, however, modify other columns in the constraining table(s). all Row-level triggers Statement-level triggers ONLY when the trigger would be fired as a result of DELETE CASCADE Single row INSERT statements do not have this mutating table problem 24