0% found this document useful (0 votes)
129 views21 pages

Triggers Basic Sql3

Triggers allow code to be automatically executed in response to events like row insertions or updates in a database table. The code is structured as event-condition-action blocks. Common uses of triggers include auditing changes, maintaining referential integrity, and calculating derived values. Triggers must avoid mutating tables, which occur when a trigger reads and updates the same table within a transaction.

Uploaded by

saconnects
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views21 pages

Triggers Basic Sql3

Triggers allow code to be automatically executed in response to events like row insertions or updates in a database table. The code is structured as event-condition-action blocks. Common uses of triggers include auditing changes, maintaining referential integrity, and calculating derived values. Triggers must avoid mutating tables, which occur when a trigger reads and updates the same table within a transaction.

Uploaded by

saconnects
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 21

Triggers in ORACLE9i

Sanjay choudhary sanconnects@yahoo.co.in

Event-Condition-Action (ECA)

Event occurs in databases


addition SQL

of new row, deletion of row by DBMS

Conditions are checked


condition

Actions 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)
2

Database Triggers in SQL


Not specified in SQL-92, but standardized in SQL3


(SQL1999)

Available in most enterprise DBMSs (Oracle, IBM DB2, MS SQL server) and some public domain DBMSs (Postgres)

but not present in smaller desktop (Oracle Lite) and public domain DBMS (MySQL)

Some vendor DBMS permit native extensions to SQL for specifying the triggers

e.g. PL/SQL in Oracle, Transact SQL in MS SQL Server

Some DBMS also general purpose programming language instead of SQL

e.g. C/C++ in Poet, Java in Oracle, C#/VB in SQL Server for example also to views as in Oracle
3

Some DBMS extend the triggers beyond tables

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)
4

Statement and Row Triggers


Example 1: Monitoring Statement Events
SQL> INSERT INTO dept (deptno, dname, loc) 2 VALUES (50, 'EDUCATION', 'NEW YORK');

Execute only once even if multiple rows affected Example 2: Monitoring Row Events
SQL> UPDATE emp 2 SET sal = sal * 1.1 3 WHERE deptno = 30;

Execute for each row of table affected by event


5

Firing Sequence of Database Triggers on Multiple Rows


EMP table
EMPNO
7839 7698 7788 BEFORE statement trigger

ENAME
KING BLAKE SMITH

DEPTNO
30 30 30 BEFORE row trigger AFTER row trigger BEFORE row trigger AFTER row trigger BEFORE row trigger AFTER row trigger AFTER statement trigger
6

Example: Logging Operations


SQL> 2 3 4 5 6 7 8 CREATE TRIGGER increase_salary_trg BEFORE UPDATE OF sal ON emp BEGIN INSERT INTO sal_hist(increased, changedOn) VALUES (YES, SYSDATE); END; /

Trigger name: Timing: Triggering event: Target: Trigger action:

increase_salary_trg BEFORE executing the statement UPDATE of sal column emp table INSERT values INTO sal_hist table
9

Example: Calculating Derived Columns


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: Timing: Triggering event: Filtering condition: Target: Trigger parameters: Trigger action:

derive_commission_trg BEFORE executing the statement UPDATE of sal column job = SALESMAN emp table old, new calculate the new commission to be updated

11

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
12

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
13

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 Access Control

e.g. the number of items in the trolley should correspond to the current session selection e.g. checking user privileges when accessing sensitive information14

Security

Auditing Table Operations


USER_NAME SCOTT SCOTT JONES TABLE_NAME COLUMN_NAME EMP EMP SAL EMP INS 1 0 UPD 1 1 0 DEL 1 1

continuation
MAX_INS 5 5 MAX_UPD 5 5 0 MAX_DEL 5 1

15

Example: 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.

16

Example: Tracing Record Value Changes


USER_NAME EGRAVINA NGREENBE TIMESTAMP

12-SEP-04
10-AUG-04

ID OLD_LAST_NAME NEW_LAST_NAME 7950 NULL HUTTON 7844 MAGEE TURNER

continuation
OLD_TITL E NULL CLERK NEW_TITLE OLD_SALARY NULL ANALYST SALESMAN 1100 NEW_SALARY 3500 1100

17

Example: 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; 12 /

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.

18

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 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.

19

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
20

Example: Mutating Table


SQL> 2 3 4 5 6 7 8 9 10 CREATE OR REPLACE TRIGGER emp_count AFTER DELETE ON emp FOR EACH ROW DECLARE num INTEGER; BEGIN SELECT COUNT(*) INTO num FROM emp; DBMS_OUTPUT.PUT_LINE(' There are now ' || num || ' employees.'); END; /
Under the bar is code entered in SQL-PLUS which triggers cascade_updates in this case. Triggers are not executed directly.

SQL> DELETE FROM emp 2 WHERE deptno = 30;

ERROR at line 1: ORA-04091: table CGMA2.EMP is mutating, trigger/ function may not see it
21

Example: Mutating Table (fixed)


SQL> 2 3 4 5 6 7 8 9 10 CREATE OR REPLACE TRIGGER emp_count AFTER DELETE ON emp Now the trigger becomes a statement trigger -- FOR EACH ROW and the EMP table is no longer mutating. DECLARE num INTEGER; BEGIN SELECT COUNT(*) INTO num FROM emp; DBMS_OUTPUT.PUT_LINE(' There are now ' || num || ' employees.'); END; / WHERE deptno = 30;

SQL> DELETE FROM emp

There are now 8 employees. 6 rows deleted.


22

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
23

Triggers in SQL99 The End


CS561

24

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy