Published on

Introduction to database lecture# 11: This lecture is all about Triggers in SQL and more...

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Triggers in SQL1Fall 2001 Database Systems 1Triggers• Assertions– Assertions describe rules that should hold for a givendatabase.– An assertion is checked anytime a table mentioned in it ischanged.– If an assertion is violated, then the change that causedthe violation is rejected.• Triggers– Triggers explicitly specify when they should be checked(i.e. insert, delete, update)– They describe a condition that activates the trigger if itevaluates to true– Triggers describe what is to be done upon activationFall 2001 Database Systems 2Designing triggers• Use triggers to guarantee that when a specific operation is performed,related actions are performed.• Do not define triggers that duplicate the functionality already built intoOracle. For example, do not define triggers to enforce data integrity rulesthat can be easily enforced using declarative integrity constraints.• Limit the size of triggers. If the logic for your trigger requires much morethan 60 lines of PL/SQL code, then it is better to include most of the code ina stored procedure and call the procedure from the trigger.• Use triggers only for centralized, global operations that should be fired forthe triggering statement, regardless of which user or database applicationissues the statement.• Do not create recursive triggers. For example, creating an AFTERUPDATE statement trigger on the Emp_tab table that itself issues anUPDATE statement on Emp_tab, causes the trigger to fire recursively until ithas run out of memory.• Use triggers on DATABASE judiciously. They are executed for every userevery time the event occurs on which the trigger is created.
  2. 2. Triggers in SQL2Fall 2001 Database Systems 3ExampleCREATE OR REPLACE TRIGGER Print_salary_changesBEFORE DELETE OR INSERT OR UPDATE ON Emp_tabFOR EACH ROWWHEN (new.Empno > 0)DECLARE sal_diff number;BEGINsal_diff := :new.sal - :old.sal;dbms_output.put(Old salary: || :old.sal);dbms_output.put( New salary: || :new.sal);dbms_output.put_line( Difference || sal_diff);END;/Fall 2001 Database Systems 4Triggers – activation• A trigger can be activated BEFORE/AFTER/INSTEAD OF anactivating event, usually insert/delete/update to one or morerelations• The action can refer to both old and new values of tuples that wereinserted/deleted/updated in the event that triggered the action.CREATE TRIGGER probation_triggerAFTER UPDATE OF gpa ON student• A condition may include a WHEN clause– the trigger action is executed only if the condition holds when thetriggering event occurs• The WHEN clause takes any boolean conditionWHEN (gpa < 2.0)
  3. 3. Triggers in SQL3Fall 2001 Database Systems 5Trigger - course of action• The programmer has the option of specifying that the action is performedeither– once for each modified tuple, or– once for all the tuples that are changed in one database operationFOR EACH ROWUPDATE studentSET probation_date = SYSDATEWHERE student.sid = OldTuple.sid• The trigger body can use any valid PL/SQL statement, IF THEN ELSE,WHILE, etc.Fall 2001 Database Systems 6Trigger - exceptions• If a predefined or user-defined error condition orexception is raised during the execution of a triggerbody, then all effects of the trigger body, as well as thetriggering statement, are rolled back (unless the error istrapped by an exception handler).• Therefore, a trigger body can prevent the execution ofthe triggering statement by raising an exception.• User-defined exceptions are commonly used in triggersthat enforce complex security authorizations or integrityconstraints.
  4. 4. Triggers in SQL4Fall 2001 Database Systems 7Triggers - row level• Insertions create new tuples– There is no corresponding “old” value• Updates change a tuple from an old value to a new value– You can refer to both values: “old” and “new” of the tuple in thetrigger• Deletes remove a tuple– There is no new value for the tuple (it is null)• Old/New values can only be accessed for each row,statement level triggers cannot access values ofindividual rows that are being changed.Fall 2001 Database Systems 8Triggers• Activation– BEFORE -- the WHEN condition is tested before the triggeringevent• if the condition is true, the trigger action is executed• then the event that triggered the update is executed– INSTEAD OF -- the action is executed if the WHEN condition ismet• the triggering event is never executed.– AFTER – the action is executed if the WHEN condition is metafter the triggering event is completed.• In BEFORE/AFTER trigger, the triggering event is rejected only if anexception is raised.
  5. 5. Triggers in SQL5Fall 2001 Database Systems 9Mutating tables• A mutating table is a table that is currently being modified by an UPDATE,DELETE, or INSERT statement, or it is a table that might need to beupdated by the effects of a declarative DELETE CASCADE referentialintegrity constraint.• A constraining table is a table that a triggering statement might need to readeither directly, for an SQL statement, or indirectly, for a declarativereferential integrity constraint.• A table is mutating or constraining only to the session that issued thestatement in progress.• Tables are never considered mutating or constraining for statement triggersunless the trigger is fired as the result of a DELETE CASCADE.• Views are not considered mutating or constraining in INSTEAD OF triggers.Fall 2001 Database Systems 10Mutating tables• For all row triggers, or for statement triggers that were fired as theresult of a DELETE CASCADE:– The SQL statements of a trigger cannot read from (query) ormodify a mutating table of the triggering statement.– The statements of a trigger cannot change the PRIMARY,FOREIGN, or UNIQUE KEY columns of a constraining table ofthe triggering statement.• There is an exception to this restriction: For a single row INSERT,constraining tables are mutating for AFTER row triggers, but not forBEFORE row triggers. INSERT statements that involve more thanone row, such as INSERT INTO Emp_tab SELECT..., are notconsidered single row inserts, even if they only result in one rowbeing inserted.• These restrictions prevent a trigger from seeing an inconsistent setof data.
  6. 6. Triggers in SQL6Fall 2001 Database Systems 11Mutating tablesFall 2001 Database Systems 12ExampleTOOK(ssn, cid, semester, year,section, grade)Students may not enroll in more than one sectionof a class in the same semester and year. If thishappens, delete all records for this student inother sections and insert him/her in the newsection.
  7. 7. Triggers in SQL7Fall 2001 Database Systems 13ExampleCREATE OR REPLACE TRIGGER took_trgAFTER INSERT ON tookREFERENCING NEW AS xFOR EACH ROWBEGINDELETE FROM took tWHERE t.cid = :x.cid AND t.semester=:x.semester ANDt.year = :x.year AND t.ssn = :x.ssn ANDt.section <> :x.section ;END ;/Problem: tookis mutating!Fall 2001 Database Systems 14Example – correct solutionCREATE VIEW tookv AS SELECT * FROM took ;CREATE OR REPLACE TRIGGER took_trgINSTEAD OF INSERT ON tookvREFERENCING NEW AS xFOR EACH ROWBEGINDELETE FROM took tWHERE t.cid = :x.cid AND t.semester=:x.semester ANDt.year = :x.year AND t.ssn = :x.ssn ANDt.section <> :x.section ;INSERT INTO took(cid, semester, year, section, ssn)VALUES(:x.cid,:x.semester,:x.year,:x.section,:x.ssn) ;END ;/
  8. 8. Triggers in SQL8Fall 2001 Database Systems 15SQL EnvironmentSchemaSchemaCatalogCatalogCluster = maximumscope of a DBoperationClusterEnvironment =installation ofDBMS• A schema containstables, views, assertions,domains,indices, etc.• A catalog contains acollection of schemas• A cluster is a collection ofcatalogs.– each user has a clusterthat is the set of allcatalogs accessible tothe user• An environment is aninstallation of a DBMSFall 2001 Database Systems 16System catalogs• All DBMSs maintain system catalogs as ordinaryrelations– these tables can be queried using SQL in the sameway as any ordinary table• For ORACLE:– ALL_ALL_TABLES (OWNER, TABLE_NAME, … )– ALL_COL_PRIVS(GRANTOR, GRANTEE, TABLE_SCHEMA,TABLE_NAME, COLUMN_NAME, PRIVILEGE, GRANTABLE)– also ALL_TAB_PRIVS– ALL_CONSTRAINTS (OWNER, CONSTRAINT_NAME,CONSTRAINT_TYPE, TABLE_NAME, SEARCH_CONDITION,DELETE_RULE, STATUS, DEFERRABLE, … )– ALL_VIEWS, ALL_TABLES, ALL_USERS, ALL_ROLES, etc.