SlideShare una empresa de Scribd logo
1 de 8
Triggers in SQL
1
Fall 2001 Database Systems 1
Triggers
• Assertions
– Assertions describe rules that should hold for a given
database.
– An assertion is checked anytime a table mentioned in it is
changed.
– If an assertion is violated, then the change that caused
the 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 it
evaluates to true
– Triggers describe what is to be done upon activation
Fall 2001 Database Systems 2
Designing 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 into
Oracle. For example, do not define triggers to enforce data integrity rules
that can be easily enforced using declarative integrity constraints.
• Limit the size of triggers. If the logic for your trigger requires much more
than 60 lines of PL/SQL code, then it is better to include most of the code in
a stored procedure and call the procedure from the trigger.
• Use triggers only for centralized, global operations that should be fired for
the triggering statement, regardless of which user or database application
issues the statement.
• Do not create recursive triggers. For example, creating an AFTER
UPDATE statement trigger on the Emp_tab table that itself issues an
UPDATE statement on Emp_tab, causes the trigger to fire recursively until it
has run out of memory.
• Use triggers on DATABASE judiciously. They are executed for every user
every time the event occurs on which the trigger is created.
Triggers in SQL
2
Fall 2001 Database Systems 3
Example
CREATE OR REPLACE TRIGGER Print_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab
FOR EACH ROW
WHEN (new.Empno > 0)
DECLARE sal_diff number;
BEGIN
sal_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 4
Triggers – activation
• A trigger can be activated BEFORE/AFTER/INSTEAD OF an
activating event, usually insert/delete/update to one or more
relations
• The action can refer to both old and new values of tuples that were
inserted/deleted/updated in the event that triggered the action.
CREATE TRIGGER probation_trigger
AFTER UPDATE OF gpa ON student
• A condition may include a WHEN clause
– the trigger action is executed only if the condition holds when the
triggering event occurs
• The WHEN clause takes any boolean condition
WHEN (gpa < 2.0)
Triggers in SQL
3
Fall 2001 Database Systems 5
Trigger - course of action
• The programmer has the option of specifying that the action is performed
either
– once for each modified tuple, or
– once for all the tuples that are changed in one database operation
FOR EACH ROW
UPDATE student
SET probation_date = SYSDATE
WHERE student.sid = OldTuple.sid
• The trigger body can use any valid PL/SQL statement, IF THEN ELSE,
WHILE, etc.
Fall 2001 Database Systems 6
Trigger - exceptions
• If a predefined or user-defined error condition or
exception is raised during the execution of a trigger
body, then all effects of the trigger body, as well as the
triggering statement, are rolled back (unless the error is
trapped by an exception handler).
• Therefore, a trigger body can prevent the execution of
the triggering statement by raising an exception.
• User-defined exceptions are commonly used in triggers
that enforce complex security authorizations or integrity
constraints.
Triggers in SQL
4
Fall 2001 Database Systems 7
Triggers - 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 the
trigger
• 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 of
individual rows that are being changed.
Fall 2001 Database Systems 8
Triggers
• Activation
– BEFORE -- the WHEN condition is tested before the triggering
event
• 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 is
met
• the triggering event is never executed.
– AFTER – the action is executed if the WHEN condition is met
after the triggering event is completed.
• In BEFORE/AFTER trigger, the triggering event is rejected only if an
exception is raised.
Triggers in SQL
5
Fall 2001 Database Systems 9
Mutating 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 be
updated by the effects of a declarative DELETE CASCADE referential
integrity constraint.
• A constraining table is a table that a triggering statement might need to read
either directly, for an SQL statement, or indirectly, for a declarative
referential integrity constraint.
• A table is mutating or constraining only to the session that issued the
statement in progress.
• Tables are never considered mutating or constraining for statement triggers
unless 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 10
Mutating tables
• For all row triggers, or for statement triggers that were fired as the
result of a DELETE CASCADE:
– The SQL statements of a trigger cannot read from (query) or
modify 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 of
the triggering statement.
• There is an exception to this restriction: For a single row INSERT,
constraining tables are mutating for AFTER row triggers, but not for
BEFORE row triggers. INSERT statements that involve more than
one row, such as INSERT INTO Emp_tab SELECT..., are not
considered single row inserts, even if they only result in one row
being inserted.
• These restrictions prevent a trigger from seeing an inconsistent set
of data.
Triggers in SQL
6
Fall 2001 Database Systems 11
Mutating tables
Fall 2001 Database Systems 12
Example
TOOK(ssn, cid, semester, year,
section, grade)
Students may not enroll in more than one section
of a class in the same semester and year. If this
happens, delete all records for this student in
other sections and insert him/her in the new
section.
Triggers in SQL
7
Fall 2001 Database Systems 13
Example
CREATE OR REPLACE TRIGGER took_trg
AFTER INSERT ON took
REFERENCING NEW AS x
FOR EACH ROW
BEGIN
DELETE FROM took t
WHERE t.cid = :x.cid AND t.semester=:x.semester AND
t.year = :x.year AND t.ssn = :x.ssn AND
t.section <> :x.section ;
END ;
/
Problem: took
is mutating!
Fall 2001 Database Systems 14
Example – correct solution
CREATE VIEW tookv AS SELECT * FROM took ;
CREATE OR REPLACE TRIGGER took_trg
INSTEAD OF INSERT ON tookv
REFERENCING NEW AS x
FOR EACH ROW
BEGIN
DELETE FROM took t
WHERE t.cid = :x.cid AND t.semester=:x.semester AND
t.year = :x.year AND t.ssn = :x.ssn AND
t.section <> :x.section ;
INSERT INTO took(cid, semester, year, section, ssn)
VALUES(:x.cid,:x.semester,:x.year,:x.section,:x.ssn) ;
END ;
/
Triggers in SQL
8
Fall 2001 Database Systems 15
SQL Environment
Schema
Schema
Catalog
Catalog
Cluster = maximum
scope of a DB
operation
Cluster
Environment =
installation of
DBMS
• A schema contains
tables, views, assertions,
domains,indices, etc.
• A catalog contains a
collection of schemas
• A cluster is a collection of
catalogs.
– each user has a cluster
that is the set of all
catalogs accessible to
the user
• An environment is an
installation of a DBMS
Fall 2001 Database Systems 16
System catalogs
• All DBMSs maintain system catalogs as ordinary
relations
– these tables can be queried using SQL in the same
way 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.

Más contenido relacionado

Destacado (14)

Sql insert statement
Sql insert statementSql insert statement
Sql insert statement
 
6. triggers
6. triggers6. triggers
6. triggers
 
Sql create table statement
Sql create table statementSql create table statement
Sql create table statement
 
SAP HANA - Manually to insert_data_table
SAP HANA - Manually to insert_data_tableSAP HANA - Manually to insert_data_table
SAP HANA - Manually to insert_data_table
 
Sql wksht-7
Sql wksht-7Sql wksht-7
Sql wksht-7
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
Part 15 triggerr
Part 15  triggerrPart 15  triggerr
Part 15 triggerr
 
Sql update statement
Sql update statementSql update statement
Sql update statement
 
Sql delete, truncate, drop statements
Sql delete, truncate, drop statementsSql delete, truncate, drop statements
Sql delete, truncate, drop statements
 
Oracle Database Trigger
Oracle Database TriggerOracle Database Trigger
Oracle Database Trigger
 
SQL Tutorial - How To Create, Drop, and Truncate Table
SQL Tutorial - How To Create, Drop, and Truncate TableSQL Tutorial - How To Create, Drop, and Truncate Table
SQL Tutorial - How To Create, Drop, and Truncate Table
 
T-SQL Overview
T-SQL OverviewT-SQL Overview
T-SQL Overview
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
 

Similar a [Www.pkbulk.blogspot.com]dbms11

11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)
Simarjit Mann
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
Abdul Rahman Sherzad
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15
Syed Asrarali
 

Similar a [Www.pkbulk.blogspot.com]dbms11 (20)

Triggers.PPTX
Triggers.PPTXTriggers.PPTX
Triggers.PPTX
 
11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)
 
Lab07_Triggers.pptx
Lab07_Triggers.pptxLab07_Triggers.pptx
Lab07_Triggers.pptx
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Unit 4
Unit 4Unit 4
Unit 4
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
 
Trigger
TriggerTrigger
Trigger
 
Postgresql stored procedure
Postgresql stored procedurePostgresql stored procedure
Postgresql stored procedure
 
Sql DML
Sql DMLSql DML
Sql DML
 
Sql DML
Sql DMLSql DML
Sql DML
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
 
SQL
SQLSQL
SQL
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16
 
Triggers n Cursors.ppt
Triggers n Cursors.pptTriggers n Cursors.ppt
Triggers n Cursors.ppt
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15
 

Más de AnusAhmad

Más de AnusAhmad (20)

[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing[Www.pkbulk.blogspot.com]file and indexing
[Www.pkbulk.blogspot.com]file and indexing
 
[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12[Www.pkbulk.blogspot.com]dbms12
[Www.pkbulk.blogspot.com]dbms12
 
[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10[Www.pkbulk.blogspot.com]dbms10
[Www.pkbulk.blogspot.com]dbms10
 
[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09[Www.pkbulk.blogspot.com]dbms09
[Www.pkbulk.blogspot.com]dbms09
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07
 
[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06[Www.pkbulk.blogspot.com]dbms06
[Www.pkbulk.blogspot.com]dbms06
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05
 
[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04[Www.pkbulk.blogspot.com]dbms04
[Www.pkbulk.blogspot.com]dbms04
 
[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03[Www.pkbulk.blogspot.com]dbms03
[Www.pkbulk.blogspot.com]dbms03
 
[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02
 
[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01[Www.pkbulk.blogspot.com]dbms01
[Www.pkbulk.blogspot.com]dbms01
 
[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13[Www.pkbulk.blogspot.com]dbms13
[Www.pkbulk.blogspot.com]dbms13
 
9. java server faces
9. java server faces9. java server faces
9. java server faces
 
8. java script
8. java script8. java script
8. java script
 
7. struts
7. struts7. struts
7. struts
 
5. servlets
5. servlets5. servlets
5. servlets
 
4. jsp
4. jsp4. jsp
4. jsp
 
3. applets
3. applets3. applets
3. applets
 
2. http, html
2. http, html2. http, html
2. http, html
 
1. intro
1. intro1. intro
1. intro
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

[Www.pkbulk.blogspot.com]dbms11

  • 1. Triggers in SQL 1 Fall 2001 Database Systems 1 Triggers • Assertions – Assertions describe rules that should hold for a given database. – An assertion is checked anytime a table mentioned in it is changed. – If an assertion is violated, then the change that caused the 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 it evaluates to true – Triggers describe what is to be done upon activation Fall 2001 Database Systems 2 Designing 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 into Oracle. For example, do not define triggers to enforce data integrity rules that can be easily enforced using declarative integrity constraints. • Limit the size of triggers. If the logic for your trigger requires much more than 60 lines of PL/SQL code, then it is better to include most of the code in a stored procedure and call the procedure from the trigger. • Use triggers only for centralized, global operations that should be fired for the triggering statement, regardless of which user or database application issues the statement. • Do not create recursive triggers. For example, creating an AFTER UPDATE statement trigger on the Emp_tab table that itself issues an UPDATE statement on Emp_tab, causes the trigger to fire recursively until it has run out of memory. • Use triggers on DATABASE judiciously. They are executed for every user every time the event occurs on which the trigger is created.
  • 2. Triggers in SQL 2 Fall 2001 Database Systems 3 Example CREATE OR REPLACE TRIGGER Print_salary_changes BEFORE DELETE OR INSERT OR UPDATE ON Emp_tab FOR EACH ROW WHEN (new.Empno > 0) DECLARE sal_diff number; BEGIN sal_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 4 Triggers – activation • A trigger can be activated BEFORE/AFTER/INSTEAD OF an activating event, usually insert/delete/update to one or more relations • The action can refer to both old and new values of tuples that were inserted/deleted/updated in the event that triggered the action. CREATE TRIGGER probation_trigger AFTER UPDATE OF gpa ON student • A condition may include a WHEN clause – the trigger action is executed only if the condition holds when the triggering event occurs • The WHEN clause takes any boolean condition WHEN (gpa < 2.0)
  • 3. Triggers in SQL 3 Fall 2001 Database Systems 5 Trigger - course of action • The programmer has the option of specifying that the action is performed either – once for each modified tuple, or – once for all the tuples that are changed in one database operation FOR EACH ROW UPDATE student SET probation_date = SYSDATE WHERE student.sid = OldTuple.sid • The trigger body can use any valid PL/SQL statement, IF THEN ELSE, WHILE, etc. Fall 2001 Database Systems 6 Trigger - exceptions • If a predefined or user-defined error condition or exception is raised during the execution of a trigger body, then all effects of the trigger body, as well as the triggering statement, are rolled back (unless the error is trapped by an exception handler). • Therefore, a trigger body can prevent the execution of the triggering statement by raising an exception. • User-defined exceptions are commonly used in triggers that enforce complex security authorizations or integrity constraints.
  • 4. Triggers in SQL 4 Fall 2001 Database Systems 7 Triggers - 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 the trigger • 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 of individual rows that are being changed. Fall 2001 Database Systems 8 Triggers • Activation – BEFORE -- the WHEN condition is tested before the triggering event • 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 is met • the triggering event is never executed. – AFTER – the action is executed if the WHEN condition is met after the triggering event is completed. • In BEFORE/AFTER trigger, the triggering event is rejected only if an exception is raised.
  • 5. Triggers in SQL 5 Fall 2001 Database Systems 9 Mutating 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 be updated by the effects of a declarative DELETE CASCADE referential integrity constraint. • A constraining table is a table that a triggering statement might need to read either directly, for an SQL statement, or indirectly, for a declarative referential integrity constraint. • A table is mutating or constraining only to the session that issued the statement in progress. • Tables are never considered mutating or constraining for statement triggers unless 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 10 Mutating tables • For all row triggers, or for statement triggers that were fired as the result of a DELETE CASCADE: – The SQL statements of a trigger cannot read from (query) or modify 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 of the triggering statement. • There is an exception to this restriction: For a single row INSERT, constraining tables are mutating for AFTER row triggers, but not for BEFORE row triggers. INSERT statements that involve more than one row, such as INSERT INTO Emp_tab SELECT..., are not considered single row inserts, even if they only result in one row being inserted. • These restrictions prevent a trigger from seeing an inconsistent set of data.
  • 6. Triggers in SQL 6 Fall 2001 Database Systems 11 Mutating tables Fall 2001 Database Systems 12 Example TOOK(ssn, cid, semester, year, section, grade) Students may not enroll in more than one section of a class in the same semester and year. If this happens, delete all records for this student in other sections and insert him/her in the new section.
  • 7. Triggers in SQL 7 Fall 2001 Database Systems 13 Example CREATE OR REPLACE TRIGGER took_trg AFTER INSERT ON took REFERENCING NEW AS x FOR EACH ROW BEGIN DELETE FROM took t WHERE t.cid = :x.cid AND t.semester=:x.semester AND t.year = :x.year AND t.ssn = :x.ssn AND t.section <> :x.section ; END ; / Problem: took is mutating! Fall 2001 Database Systems 14 Example – correct solution CREATE VIEW tookv AS SELECT * FROM took ; CREATE OR REPLACE TRIGGER took_trg INSTEAD OF INSERT ON tookv REFERENCING NEW AS x FOR EACH ROW BEGIN DELETE FROM took t WHERE t.cid = :x.cid AND t.semester=:x.semester AND t.year = :x.year AND t.ssn = :x.ssn AND t.section <> :x.section ; INSERT INTO took(cid, semester, year, section, ssn) VALUES(:x.cid,:x.semester,:x.year,:x.section,:x.ssn) ; END ; /
  • 8. Triggers in SQL 8 Fall 2001 Database Systems 15 SQL Environment Schema Schema Catalog Catalog Cluster = maximum scope of a DB operation Cluster Environment = installation of DBMS • A schema contains tables, views, assertions, domains,indices, etc. • A catalog contains a collection of schemas • A cluster is a collection of catalogs. – each user has a cluster that is the set of all catalogs accessible to the user • An environment is an installation of a DBMS Fall 2001 Database Systems 16 System catalogs • All DBMSs maintain system catalogs as ordinary relations – these tables can be queried using SQL in the same way 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.