SlideShare ist ein Scribd-Unternehmen logo
1 von 59
Introduction to Triggers
Rehab Duwairi
Introduction to Triggers
• You can write triggers that fire whenever one of
the following operations occurs:
– DML statements (INSERT, UPDATE, DELETE) on a
particular table or view, issued by any user
– DDL statements (CREATE or ALTER primarily) issued
either by a particular schema/user or by any
schema/user in the database
– Database events, such as logon/logoff, errors, or
startup/shutdown, also issued either by a particular
schema/user or by any schema/user in the database
Triggers vs. Procedures
• Triggers are similar to stored procedures.
• A trigger stored in the database can include SQL
and PL/SQL or Java statements to run as a unit
and can invoke stored procedures.
• However, procedures and triggers differ in the
way that they are invoked.
• A procedure is explicitly run by a user,
application, or trigger.
• Triggers are implicitly fired by Oracle when a
triggering event occurs, no matter which user is
connected or which application is being used.
Forms triggers Vs. DB Triggers
• Oracle Forms can define, store, and run
triggers of a different sort. However, do not
confuse Oracle Forms triggers with the
triggers discussed here.
• DB triggers are independent of any
application.
How Triggers Are Used
• You can also use triggers to:
– Automatically generate derived column values
– Prevent invalid transactions
– Enforce complex security authorizations
– Enforce referential integrity across nodes in a distributed
database
– Enforce complex business rules
– Provide transparent event logging
– Provide auditing
– Maintain synchronous table replicates
– Gather statistics on table access
– Modify table data when DML statements are issued
against views
– Publish information about database events, user events,
and SQL statements to subscribing applications
Some Cautionary Notes about
Triggers
• Although triggers are useful for customizing a
database, use them only when necessary.
• Excessive use of triggers can result in
complex interdependencies, which can be
difficult to maintain in a large application.
• For example, when a trigger fires, a SQL
statement within its trigger action potentially
can fire other triggers, resulting in cascading
triggers. This can produce unintended effects
Parts of a Trigger
• A trigger has three basic parts:
– A triggering event or statement
– A trigger restriction
– A trigger action
The Triggering Event or Statement
• A triggering event or statement is the SQL
statement, database event, or user event that
causes a trigger to fire. A triggering event can be
one or more of the following:
– An INSERT, UPDATE, or DELETE statement on a specific
table (or view, in some cases)
– A CREATE, ALTER, or DROP statement on any schema
object
– A database startup or instance shutdown
– A specific error message or any error message
– A user logon or logoff
Triggering event or statement
e.g. UPDATE OF parts_on_hand ON inventory
This statement means that when the
parts_on_hand column of a row in the inventory
table is updated, fire the trigger.
• When the triggering event is an UPDATE
statement, you can include a column list to
identify which columns must be updated to fire
the trigger.
• You cannot specify a column list for INSERT and
DELETE statements, because they affect entire
rows of information.
• A triggering event can specify multiple SQL statements:
e.g. INSERT OR UPDATE OR DELETE OF inventory
• This part means that when an INSERT, UPDATE, or
DELETE statement is issued against the inventory table,
fire the trigger.
• When multiple types of SQL statements can fire a
trigger, you can use conditional predicates to detect
the type of triggering statement. In this way, you can
create a single trigger that runs different code based on
the type of statement that fires the trigger.
Trigger Restriction
• A trigger restriction specifies a Boolean
expression that must be true for the trigger to
fire.
• The trigger action is not run if the trigger
restriction evaluates to false or unknown. In the
example, the trigger restriction is:
• new.parts_on_hand < new.reorder_point
Consequently, the trigger does not fire unless the
number of available parts is less than a present
reorder amount.
Trigger Action
• A trigger action is the procedure (PL/SQL block, Java program)
that contains the SQL statements and code to be run when
the following events occur:
• A triggering statement is issued.
• The trigger restriction evaluates to true.
• Like stored procedures, a trigger action can:
– Contain SQL, PL/SQL, or Java statements
– Define PL/SQL language constructs such as variables,
constants, cursors, exceptions
– Define Java language constructs
– Call stored procedures
• If the triggers are row triggers, the statements in a trigger
action have access to column values of the row being
processed by the trigger. Correlation names provide access to
the old and new values for each column.
Types of Triggers
• Row Triggers and Statement Triggers
• BEFORE and AFTER Triggers
• INSTEAD OF Triggers
• Triggers on System Events and User Events
Row Triggers and Statement Triggers
• When you define a trigger, you can specify the
number of times the trigger action is to be
run:
– Once for every row affected by the triggering
statement, such as a trigger fired by an UPDATE
statement that updates many rows
• Once for the triggering statement, no matter
how many rows it affects
Row Triggers
• A row trigger is fired each time the table is
affected by the triggering statement.
• For example, if an UPDATE statement updates
multiple rows of a table, a row trigger is fired
once for each row affected by the UPDATE
statement.
• If a triggering statement affects no rows, a row
trigger is not run.
• Row triggers are useful if the code in the trigger
action depends on data provided by the
triggering statement or rows that are affected.
Statement Triggers
• A statement trigger is fired once on behalf of the triggering
statement, regardless of the number of rows in the table
that the triggering statement affects, even if no rows are
affected.
• For example, if a DELETE statement deletes several rows
from a table, a statement-level DELETE trigger is fired only
once.
• Statement triggers are useful if the code in the trigger
action does not depend on the data provided by the
triggering statement or the rows affected. For example, use
a statement trigger to:
– Make a complex security check on the current time or user
– Generate a single audit record
BEFORE and AFTER Triggers
• When defining a trigger, you can specify the trigger
timing—whether the trigger action is to be run before or
after the triggering statement.
• BEFORE and AFTER apply to both statement and row
triggers.
• BEFORE and AFTER triggers fired by DML statements can be
defined only on tables, not on views.
• However, triggers on the base tables of a view are fired if
an INSERT, UPDATE, or DELETE statement is issued against
the view.
• BEFORE and AFTER triggers fired by DDL statements can be
defined only on the database or a schema, not on
particular tables.
BEFORE Triggers
• BEFORE triggers run the trigger action before the
triggering statement is run. This type of trigger is
commonly used in the following situations:
– When the trigger action determines whether the
triggering statement should be allowed to complete.
Using a BEFORE trigger for this purpose, you can
eliminate unnecessary processing of the triggering
statement and its eventual rollback in cases where an
exception is raised in the trigger action.
– To derive specific column values before completing a
triggering INSERT or UPDATE statement.
AFTE R Triggers
• AFTER triggers run the trigger action after the
triggering statement is run.
Trigger Type Combinations
• BEFORE statement trigger
– Before executing the triggering statement, the trigger action is run.
• BEFORE row trigger
– Before modifying each row affected by the triggering statement and
before checking appropriate integrity constraints, the trigger action is
run, if the trigger restriction was not violated.
• AFTER statement trigger
– After executing the triggering statement and applying any deferred
integrity constraints, the trigger action is run.
• AFTER row trigger
– After modifying each row affected by the triggering statement and
possibly applying appropriate integrity constraints, the trigger action is
run for the current row provided the trigger restriction was not
violated. Unlike BEFORE row triggers, AFTER row triggers lock rows.
INSTEAD OF Triggers
• INSTEAD OF triggers provide a transparent way of
modifying views that cannot be modified directly
through DML statements (INSERT, UPDATE, and
DELETE). These triggers are called INSTEAD OF triggers
because, unlike other types of triggers, Oracle fires the
trigger instead of executing the triggering statement.
• You can write normal INSERT, UPDATE, and DELETE
statements against the view and the INSTEAD OF
trigger is fired to update the underlying tables
appropriately. INSTEAD OF triggers are activated for
each row of the view that gets modified.
Modify Views
• Modifying views can have ambiguous results:
• Deleting a row in a view could either mean
deleting it from the base table or updating some
values so that it is no longer selected by the view.
• Inserting a row in a view could either mean
inserting a new row into the base table or
updating an existing row so that it is projected by
the view.
• Updating a column in a view that involves joins
might change the semantics of other columns
that are not projected by the view.
Object views
• Object views present additional problems. For
example, a key use of object views is to represent
master/detail relationships. This operation
inevitably involves joins, but modifying joins is
inherently ambiguous.
• As a result of these ambiguities, there are many
restrictions on which views are modifiable. An
INSTEAD OF trigger can be used on object views
as well as relational views that are not otherwise
modifiable.
• A view is inherently modifiable if data can be
inserted, updated, or deleted without using
INSTEAD OF triggers and if it conforms to the
restrictions listed as follows.
• Even if the view is inherently modifiable, you
might want to perform validations on the values
being inserted, updated or deleted.
• INSTEAD OF triggers can also be used in this case.
Here the trigger code performs the validation on
the rows being modified and if valid, propagate
the changes to the underlying tables.
Views That Are Not Modifiable
• If the view query contains any of the following
constructs, the view is not inherently
modifiable and you therefore cannot perform
inserts, updates, or deletes on the view:
– Set operators
– Aggregate functions
– GROUP BY,
– The DISTINCT operator
– Joins (however, some join views are updatable)
• If a view contains pseudocolumns or
expressions, you can only update the view
with an UPDATE statement that does not refer
to any of the pseudocolumns or expressions.
Triggers on DDL Statements
• DDL triggers can be associated with the database or
with a schema. Their attributes include the system
event, the type of schema object, and its name. They
can specify simple conditions on the type and name of
the schema object, as well as functions like USERID and
USERNAME.
• DDL triggers include the following types of triggers:
– BEFORE CREATE and AFTER CREATE triggers fire when a
schema object is created in the database or schema.
– BEFORE ALTER and AFTER ALTER triggers fire when a
schema object is altered in the database or schema.
– BEFORE DROP and AFTER DROP triggers fire when a
schema object is dropped from the database or schema.
Triggers on DML Statements
• BEFORE INSERT and AFTER INSERT triggers fire for
each row inserted into the table.
• BEFORE UPDATE and AFTER UPDATE triggers fire
for each row updated in the table.
• BEFORE DELETE and AFTER DELETE triggers fire
for each row deleted from the table.
Trigger Execution
• Enabled
– An enabled trigger runs its trigger action if a
triggering statement is issued and the trigger
restriction (if any) evaluates to true.
• Disabled
– A disabled trigger does not run its trigger action,
even if a triggering statement is issued and the
trigger restriction (if any) would evaluate to true.
Syntax
CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE |
AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] |
DELETE} [OF col_name] ON table_name [REFERENCING
OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
• Where:
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an
existing trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML
operation.
• [OF col_name] − This specifies the column name that will be updated.
• [ON table_name] − This specifies the name of the table associated with
the trigger.
• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and
old values for various DML statements, such as INSERT, UPDATE, and
DELETE.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will
be executed for each row being affected. Otherwise the trigger will
execute just once when the SQL statement is executed, which is called a
table level trigger.
• WHEN (condition) − This provides a condition for rows for which the
trigger would fire. This clause is valid only for row-level triggers.
Examples
• The following program creates a row-level
trigger for the customers table that would fire
for INSERT or UPDATE or DELETE operations
performed on the CUSTOMERS table. This
trigger will display the salary difference
between the old values and new values
CREATE OR REPLACE TRIGGER
display_salary_changes BEFORE DELETE OR INSERT
OR UPDATE ON customers FOR EACH ROW WHEN
(NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' ||
:NEW.salary);
dbms_output.put_line('Salary difference: ' ||
sal_diff);
END;
/
Triggering the Trigger
INSERT INTO CUSTOMERS
(ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, 'Kriti',
22, 'HP', 7500.00 );
• The trigger will be fired:
Old salary:
New salary: 7500
Salary difference:
• The insert statement added a new record and
thus old salary is not available.
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
Old salary: 1500
New salary: 2000
Salary difference: 500
• Given:
CREATE TABLE product_price_history
(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );
CREATE TABLE product
(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );
• A trigger to store old values of a record before
updating it.
CREATE or REPLACE TRIGGER price_history_trigger
BEFORE UPDATE OF unit_price ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history
VALUES
(:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price);
END;
• Fire the trigger
UPDATE PRODUCT SET unit_price = 800 WHERE
product_id = 100;
• If you ROLLBACK the transaction before
committing to the database, the data inserted
to the table is also rolled back.
More examples
• Create table called product_check
CREATE TABLE product_Check (
Message varchar2(50),
Current_Date date );
BEFORE UPDATE, Statement Level
• This trigger will insert a record into the table
'product_check' before a sql update statement is executed,
at the statement level.
CREATE or REPLACE TRIGGER Before_Update_Stat_product
BEFORE UPDATE ON product
Begin
INSERT INTO product_check Values('Before update, statement
level', sysdate);
END;
/
BEFORE UPDATE, Row Level
• This trigger will insert a record into the table
'product_check' before each row is updated.
CREATE or REPLACE TRIGGER
Before_Upddate_Row_product BEFORE UPDATE ON
product FOR EACH ROW
BEGIN
INSERT INTO product_check Values('Before update row
level', sysdate);
END;
/
AFTER UPDATE, Statement Level
• This trigger will insert a record into the table
'product_check' after a sql update statement is
executed, at the statement level.
CREATE or REPLACE TRIGGER After_Update_Stat_product
AFTER UPDATE ON product
BEGIN
INSERT INTO product_check Values('After update,
statement level', sysdate);
End; /
AFTER UPDATE, Row Level
• This trigger will insert a record into the table
'product_check' after each row is updated.
CREATE or REPLACE TRIGGER After_Update_Row_product
AFTER insert On product FOR EACH ROW
BEGIN
INSERT INTO product_check Values('After update, Row
level', sysdate);
END;
/
Fire the Triggers
• Now lets execute a update statement on table
product.
UPDATE PRODUCT
SET unit_price = 800
WHERE product_id in (100,101);
Check the effects of firing the triggers
• Lets check the data in 'product_check' table to
see the order in which the trigger is fired.
SELECT * FROM product_check;
Product_Check table
How To know Information about
Triggers?
• We can use the data dictionary view
'USER_TRIGGERS' to obtain information about
any trigger.
• The below statement shows the structure of
the view 'USER_TRIGGERS'
DESC USER_TRIGGERS;
Example on DDL trigger
• CREATE OR REPLACE TRIGGER no_xtabs
BEFORE CREATE
ON SCHEMA
DECLARE
x user_tables.table_name%TYPE;
BEGIN
SELECT ora_dict_obj_name
INTO x
FROM DUAL;
IF SUBSTR(x, 1, 1) = 'X' THEN
RAISE_APPLICATION_ERROR(-20099, 'Table Names Can Not
Start With The Letter X');
END IF;
END no_xtabs;
File the trigger
CREATE TABLE ztest (
testcol VARCHAR2(20));
CREATE TABLE xtest (
testcol VARCHAR2(20));
Uses/Advantages
– To move application logic and business rules into
database
– This allows more functionality for DBAs to
establish vital constraints/rules of applications
– Rules managed in some central “place”
– Rules automatically enforced by DBMS, no matter
which applications later come on line
Bad things can happen
CREATE TRIGGER Bad-trigger
AFTER UPDATE OF price IN Product
REFERENCING OLD AS OldTuple
NEW AS NewTuple
WHEN (NewTuple.price > 50)
UPDATE Product
SET price = NewTuple.price * 2
WHERE name = NewTuple.name
FOR EACH ROW
• END

Weitere ähnliche Inhalte

Ähnlich wie Triggers.PPTX (20)

Trigger
TriggerTrigger
Trigger
 
Sql triggers
Sql triggersSql triggers
Sql triggers
 
Lab07_Triggers.pptx
Lab07_Triggers.pptxLab07_Triggers.pptx
Lab07_Triggers.pptx
 
Introduction to triggers
Introduction to triggersIntroduction to triggers
Introduction to triggers
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
 
Postgresql stored procedure
Postgresql stored procedurePostgresql stored procedure
Postgresql stored procedure
 
Trigger
TriggerTrigger
Trigger
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Training
 
Unit 4
Unit 4Unit 4
Unit 4
 
SQL
SQLSQL
SQL
 
Oracle: Cursors
Oracle: CursorsOracle: Cursors
Oracle: Cursors
 
Oracle:Cursors
Oracle:CursorsOracle:Cursors
Oracle:Cursors
 
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
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
IR SQLite Session #3
IR SQLite Session #3IR SQLite Session #3
IR SQLite Session #3
 

Mehr von ansariparveen06

discrete mathematics binary%20trees.pptx
discrete mathematics binary%20trees.pptxdiscrete mathematics binary%20trees.pptx
discrete mathematics binary%20trees.pptxansariparveen06
 
Introduction to Arduino 16822775 (2).ppt
Introduction to Arduino 16822775 (2).pptIntroduction to Arduino 16822775 (2).ppt
Introduction to Arduino 16822775 (2).pptansariparveen06
 
Fundamentals of programming Arduino-Wk2.ppt
Fundamentals of programming Arduino-Wk2.pptFundamentals of programming Arduino-Wk2.ppt
Fundamentals of programming Arduino-Wk2.pptansariparveen06
 
Combinational_Logic_Circuit.pptx
Combinational_Logic_Circuit.pptxCombinational_Logic_Circuit.pptx
Combinational_Logic_Circuit.pptxansariparveen06
 
presentation_python_7_1569170870_375360.pptx
presentation_python_7_1569170870_375360.pptxpresentation_python_7_1569170870_375360.pptx
presentation_python_7_1569170870_375360.pptxansariparveen06
 
BCom-Sem2-Marketing-Digital-payment-Presentation.pptx
BCom-Sem2-Marketing-Digital-payment-Presentation.pptxBCom-Sem2-Marketing-Digital-payment-Presentation.pptx
BCom-Sem2-Marketing-Digital-payment-Presentation.pptxansariparveen06
 
May14ProcessScheduling.ppt
May14ProcessScheduling.pptMay14ProcessScheduling.ppt
May14ProcessScheduling.pptansariparveen06
 
UNIPROCESS SCHEDULING.pptx
UNIPROCESS SCHEDULING.pptxUNIPROCESS SCHEDULING.pptx
UNIPROCESS SCHEDULING.pptxansariparveen06
 
1-introduction-to-dart-programming.pptx
1-introduction-to-dart-programming.pptx1-introduction-to-dart-programming.pptx
1-introduction-to-dart-programming.pptxansariparveen06
 

Mehr von ansariparveen06 (20)

discrete mathematics binary%20trees.pptx
discrete mathematics binary%20trees.pptxdiscrete mathematics binary%20trees.pptx
discrete mathematics binary%20trees.pptx
 
Introduction to Arduino 16822775 (2).ppt
Introduction to Arduino 16822775 (2).pptIntroduction to Arduino 16822775 (2).ppt
Introduction to Arduino 16822775 (2).ppt
 
Fundamentals of programming Arduino-Wk2.ppt
Fundamentals of programming Arduino-Wk2.pptFundamentals of programming Arduino-Wk2.ppt
Fundamentals of programming Arduino-Wk2.ppt
 
pscheduling.ppt
pscheduling.pptpscheduling.ppt
pscheduling.ppt
 
kmap.pptx
kmap.pptxkmap.pptx
kmap.pptx
 
Combinational_Logic_Circuit.pptx
Combinational_Logic_Circuit.pptxCombinational_Logic_Circuit.pptx
Combinational_Logic_Circuit.pptx
 
presentation_python_7_1569170870_375360.pptx
presentation_python_7_1569170870_375360.pptxpresentation_python_7_1569170870_375360.pptx
presentation_python_7_1569170870_375360.pptx
 
BCom-Sem2-Marketing-Digital-payment-Presentation.pptx
BCom-Sem2-Marketing-Digital-payment-Presentation.pptxBCom-Sem2-Marketing-Digital-payment-Presentation.pptx
BCom-Sem2-Marketing-Digital-payment-Presentation.pptx
 
dsa.ppt
dsa.pptdsa.ppt
dsa.ppt
 
11-IOManagement.ppt
11-IOManagement.ppt11-IOManagement.ppt
11-IOManagement.ppt
 
May14ProcessScheduling.ppt
May14ProcessScheduling.pptMay14ProcessScheduling.ppt
May14ProcessScheduling.ppt
 
UNIPROCESS SCHEDULING.pptx
UNIPROCESS SCHEDULING.pptxUNIPROCESS SCHEDULING.pptx
UNIPROCESS SCHEDULING.pptx
 
1-introduction-to-dart-programming.pptx
1-introduction-to-dart-programming.pptx1-introduction-to-dart-programming.pptx
1-introduction-to-dart-programming.pptx
 
CHAP4.pptx
CHAP4.pptxCHAP4.pptx
CHAP4.pptx
 
green IT cooling.pptx
green IT cooling.pptxgreen IT cooling.pptx
green IT cooling.pptx
 
06-Deadlocks.ppt
06-Deadlocks.ppt06-Deadlocks.ppt
06-Deadlocks.ppt
 
chp9 green IT.pptx
chp9 green IT.pptxchp9 green IT.pptx
chp9 green IT.pptx
 
regex.ppt
regex.pptregex.ppt
regex.ppt
 
BOM.ppt
BOM.pptBOM.ppt
BOM.ppt
 
Cooling.pptx
Cooling.pptxCooling.pptx
Cooling.pptx
 

Kürzlich hochgeladen

Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 

Kürzlich hochgeladen (20)

Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 

Triggers.PPTX

  • 2. Introduction to Triggers • You can write triggers that fire whenever one of the following operations occurs: – DML statements (INSERT, UPDATE, DELETE) on a particular table or view, issued by any user – DDL statements (CREATE or ALTER primarily) issued either by a particular schema/user or by any schema/user in the database – Database events, such as logon/logoff, errors, or startup/shutdown, also issued either by a particular schema/user or by any schema/user in the database
  • 3. Triggers vs. Procedures • Triggers are similar to stored procedures. • A trigger stored in the database can include SQL and PL/SQL or Java statements to run as a unit and can invoke stored procedures. • However, procedures and triggers differ in the way that they are invoked. • A procedure is explicitly run by a user, application, or trigger. • Triggers are implicitly fired by Oracle when a triggering event occurs, no matter which user is connected or which application is being used.
  • 4. Forms triggers Vs. DB Triggers • Oracle Forms can define, store, and run triggers of a different sort. However, do not confuse Oracle Forms triggers with the triggers discussed here. • DB triggers are independent of any application.
  • 5. How Triggers Are Used • You can also use triggers to: – Automatically generate derived column values – Prevent invalid transactions – Enforce complex security authorizations – Enforce referential integrity across nodes in a distributed database – Enforce complex business rules – Provide transparent event logging – Provide auditing – Maintain synchronous table replicates – Gather statistics on table access – Modify table data when DML statements are issued against views – Publish information about database events, user events, and SQL statements to subscribing applications
  • 6. Some Cautionary Notes about Triggers • Although triggers are useful for customizing a database, use them only when necessary. • Excessive use of triggers can result in complex interdependencies, which can be difficult to maintain in a large application. • For example, when a trigger fires, a SQL statement within its trigger action potentially can fire other triggers, resulting in cascading triggers. This can produce unintended effects
  • 7.
  • 8. Parts of a Trigger • A trigger has three basic parts: – A triggering event or statement – A trigger restriction – A trigger action
  • 9.
  • 10. The Triggering Event or Statement • A triggering event or statement is the SQL statement, database event, or user event that causes a trigger to fire. A triggering event can be one or more of the following: – An INSERT, UPDATE, or DELETE statement on a specific table (or view, in some cases) – A CREATE, ALTER, or DROP statement on any schema object – A database startup or instance shutdown – A specific error message or any error message – A user logon or logoff
  • 11. Triggering event or statement e.g. UPDATE OF parts_on_hand ON inventory This statement means that when the parts_on_hand column of a row in the inventory table is updated, fire the trigger. • When the triggering event is an UPDATE statement, you can include a column list to identify which columns must be updated to fire the trigger. • You cannot specify a column list for INSERT and DELETE statements, because they affect entire rows of information.
  • 12. • A triggering event can specify multiple SQL statements: e.g. INSERT OR UPDATE OR DELETE OF inventory • This part means that when an INSERT, UPDATE, or DELETE statement is issued against the inventory table, fire the trigger. • When multiple types of SQL statements can fire a trigger, you can use conditional predicates to detect the type of triggering statement. In this way, you can create a single trigger that runs different code based on the type of statement that fires the trigger.
  • 13. Trigger Restriction • A trigger restriction specifies a Boolean expression that must be true for the trigger to fire. • The trigger action is not run if the trigger restriction evaluates to false or unknown. In the example, the trigger restriction is: • new.parts_on_hand < new.reorder_point Consequently, the trigger does not fire unless the number of available parts is less than a present reorder amount.
  • 14. Trigger Action • A trigger action is the procedure (PL/SQL block, Java program) that contains the SQL statements and code to be run when the following events occur: • A triggering statement is issued. • The trigger restriction evaluates to true. • Like stored procedures, a trigger action can: – Contain SQL, PL/SQL, or Java statements – Define PL/SQL language constructs such as variables, constants, cursors, exceptions – Define Java language constructs – Call stored procedures • If the triggers are row triggers, the statements in a trigger action have access to column values of the row being processed by the trigger. Correlation names provide access to the old and new values for each column.
  • 15. Types of Triggers • Row Triggers and Statement Triggers • BEFORE and AFTER Triggers • INSTEAD OF Triggers • Triggers on System Events and User Events
  • 16. Row Triggers and Statement Triggers • When you define a trigger, you can specify the number of times the trigger action is to be run: – Once for every row affected by the triggering statement, such as a trigger fired by an UPDATE statement that updates many rows • Once for the triggering statement, no matter how many rows it affects
  • 17. Row Triggers • A row trigger is fired each time the table is affected by the triggering statement. • For example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row affected by the UPDATE statement. • If a triggering statement affects no rows, a row trigger is not run. • Row triggers are useful if the code in the trigger action depends on data provided by the triggering statement or rows that are affected.
  • 18. Statement Triggers • A statement trigger is fired once on behalf of the triggering statement, regardless of the number of rows in the table that the triggering statement affects, even if no rows are affected. • For example, if a DELETE statement deletes several rows from a table, a statement-level DELETE trigger is fired only once. • Statement triggers are useful if the code in the trigger action does not depend on the data provided by the triggering statement or the rows affected. For example, use a statement trigger to: – Make a complex security check on the current time or user – Generate a single audit record
  • 19. BEFORE and AFTER Triggers • When defining a trigger, you can specify the trigger timing—whether the trigger action is to be run before or after the triggering statement. • BEFORE and AFTER apply to both statement and row triggers. • BEFORE and AFTER triggers fired by DML statements can be defined only on tables, not on views. • However, triggers on the base tables of a view are fired if an INSERT, UPDATE, or DELETE statement is issued against the view. • BEFORE and AFTER triggers fired by DDL statements can be defined only on the database or a schema, not on particular tables.
  • 20. BEFORE Triggers • BEFORE triggers run the trigger action before the triggering statement is run. This type of trigger is commonly used in the following situations: – When the trigger action determines whether the triggering statement should be allowed to complete. Using a BEFORE trigger for this purpose, you can eliminate unnecessary processing of the triggering statement and its eventual rollback in cases where an exception is raised in the trigger action. – To derive specific column values before completing a triggering INSERT or UPDATE statement.
  • 21. AFTE R Triggers • AFTER triggers run the trigger action after the triggering statement is run.
  • 22. Trigger Type Combinations • BEFORE statement trigger – Before executing the triggering statement, the trigger action is run. • BEFORE row trigger – Before modifying each row affected by the triggering statement and before checking appropriate integrity constraints, the trigger action is run, if the trigger restriction was not violated. • AFTER statement trigger – After executing the triggering statement and applying any deferred integrity constraints, the trigger action is run. • AFTER row trigger – After modifying each row affected by the triggering statement and possibly applying appropriate integrity constraints, the trigger action is run for the current row provided the trigger restriction was not violated. Unlike BEFORE row triggers, AFTER row triggers lock rows.
  • 23. INSTEAD OF Triggers • INSTEAD OF triggers provide a transparent way of modifying views that cannot be modified directly through DML statements (INSERT, UPDATE, and DELETE). These triggers are called INSTEAD OF triggers because, unlike other types of triggers, Oracle fires the trigger instead of executing the triggering statement. • You can write normal INSERT, UPDATE, and DELETE statements against the view and the INSTEAD OF trigger is fired to update the underlying tables appropriately. INSTEAD OF triggers are activated for each row of the view that gets modified.
  • 24. Modify Views • Modifying views can have ambiguous results: • Deleting a row in a view could either mean deleting it from the base table or updating some values so that it is no longer selected by the view. • Inserting a row in a view could either mean inserting a new row into the base table or updating an existing row so that it is projected by the view. • Updating a column in a view that involves joins might change the semantics of other columns that are not projected by the view.
  • 25. Object views • Object views present additional problems. For example, a key use of object views is to represent master/detail relationships. This operation inevitably involves joins, but modifying joins is inherently ambiguous. • As a result of these ambiguities, there are many restrictions on which views are modifiable. An INSTEAD OF trigger can be used on object views as well as relational views that are not otherwise modifiable.
  • 26. • A view is inherently modifiable if data can be inserted, updated, or deleted without using INSTEAD OF triggers and if it conforms to the restrictions listed as follows. • Even if the view is inherently modifiable, you might want to perform validations on the values being inserted, updated or deleted. • INSTEAD OF triggers can also be used in this case. Here the trigger code performs the validation on the rows being modified and if valid, propagate the changes to the underlying tables.
  • 27. Views That Are Not Modifiable • If the view query contains any of the following constructs, the view is not inherently modifiable and you therefore cannot perform inserts, updates, or deletes on the view: – Set operators – Aggregate functions – GROUP BY, – The DISTINCT operator – Joins (however, some join views are updatable)
  • 28. • If a view contains pseudocolumns or expressions, you can only update the view with an UPDATE statement that does not refer to any of the pseudocolumns or expressions.
  • 29. Triggers on DDL Statements • DDL triggers can be associated with the database or with a schema. Their attributes include the system event, the type of schema object, and its name. They can specify simple conditions on the type and name of the schema object, as well as functions like USERID and USERNAME. • DDL triggers include the following types of triggers: – BEFORE CREATE and AFTER CREATE triggers fire when a schema object is created in the database or schema. – BEFORE ALTER and AFTER ALTER triggers fire when a schema object is altered in the database or schema. – BEFORE DROP and AFTER DROP triggers fire when a schema object is dropped from the database or schema.
  • 30. Triggers on DML Statements • BEFORE INSERT and AFTER INSERT triggers fire for each row inserted into the table. • BEFORE UPDATE and AFTER UPDATE triggers fire for each row updated in the table. • BEFORE DELETE and AFTER DELETE triggers fire for each row deleted from the table.
  • 31. Trigger Execution • Enabled – An enabled trigger runs its trigger action if a triggering statement is issued and the trigger restriction (if any) evaluates to true. • Disabled – A disabled trigger does not run its trigger action, even if a triggering statement is issued and the trigger restriction (if any) would evaluate to true.
  • 32. Syntax CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) DECLARE Declaration-statements BEGIN Executable-statements EXCEPTION Exception-handling-statements END;
  • 33. • Where: • CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name. • {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is used for creating trigger on a view. • {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation. • [OF col_name] − This specifies the column name that will be updated. • [ON table_name] − This specifies the name of the table associated with the trigger. • [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE. • [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger. • WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers.
  • 35. • The following program creates a row-level trigger for the customers table that would fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values
  • 36. CREATE OR REPLACE TRIGGER display_salary_changes BEFORE DELETE OR INSERT OR UPDATE ON customers FOR EACH ROW WHEN (NEW.ID > 0) DECLARE sal_diff number; BEGIN sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line('Old salary: ' || :OLD.salary); dbms_output.put_line('New salary: ' || :NEW.salary); dbms_output.put_line('Salary difference: ' || sal_diff); END; /
  • 37. Triggering the Trigger INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, 'Kriti', 22, 'HP', 7500.00 ); • The trigger will be fired: Old salary: New salary: 7500 Salary difference: • The insert statement added a new record and thus old salary is not available.
  • 38. UPDATE customers SET salary = salary + 500 WHERE id = 2; Old salary: 1500 New salary: 2000 Salary difference: 500
  • 39. • Given: CREATE TABLE product_price_history (product_id number(5), product_name varchar2(32), supplier_name varchar2(32), unit_price number(7,2) ); CREATE TABLE product (product_id number(5), product_name varchar2(32), supplier_name varchar2(32), unit_price number(7,2) );
  • 40. • A trigger to store old values of a record before updating it. CREATE or REPLACE TRIGGER price_history_trigger BEFORE UPDATE OF unit_price ON product FOR EACH ROW BEGIN INSERT INTO product_price_history VALUES (:old.product_id, :old.product_name, :old.supplier_name, :old.unit_price); END;
  • 41. • Fire the trigger UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100; • If you ROLLBACK the transaction before committing to the database, the data inserted to the table is also rolled back.
  • 42. More examples • Create table called product_check CREATE TABLE product_Check ( Message varchar2(50), Current_Date date );
  • 43. BEFORE UPDATE, Statement Level • This trigger will insert a record into the table 'product_check' before a sql update statement is executed, at the statement level. CREATE or REPLACE TRIGGER Before_Update_Stat_product BEFORE UPDATE ON product Begin INSERT INTO product_check Values('Before update, statement level', sysdate); END; /
  • 44. BEFORE UPDATE, Row Level • This trigger will insert a record into the table 'product_check' before each row is updated. CREATE or REPLACE TRIGGER Before_Upddate_Row_product BEFORE UPDATE ON product FOR EACH ROW BEGIN INSERT INTO product_check Values('Before update row level', sysdate); END; /
  • 45. AFTER UPDATE, Statement Level • This trigger will insert a record into the table 'product_check' after a sql update statement is executed, at the statement level. CREATE or REPLACE TRIGGER After_Update_Stat_product AFTER UPDATE ON product BEGIN INSERT INTO product_check Values('After update, statement level', sysdate); End; /
  • 46. AFTER UPDATE, Row Level • This trigger will insert a record into the table 'product_check' after each row is updated. CREATE or REPLACE TRIGGER After_Update_Row_product AFTER insert On product FOR EACH ROW BEGIN INSERT INTO product_check Values('After update, Row level', sysdate); END; /
  • 47. Fire the Triggers • Now lets execute a update statement on table product. UPDATE PRODUCT SET unit_price = 800 WHERE product_id in (100,101);
  • 48. Check the effects of firing the triggers • Lets check the data in 'product_check' table to see the order in which the trigger is fired. SELECT * FROM product_check;
  • 49.
  • 51. How To know Information about Triggers? • We can use the data dictionary view 'USER_TRIGGERS' to obtain information about any trigger. • The below statement shows the structure of the view 'USER_TRIGGERS' DESC USER_TRIGGERS;
  • 52.
  • 53. Example on DDL trigger • CREATE OR REPLACE TRIGGER no_xtabs BEFORE CREATE ON SCHEMA DECLARE x user_tables.table_name%TYPE; BEGIN SELECT ora_dict_obj_name INTO x FROM DUAL; IF SUBSTR(x, 1, 1) = 'X' THEN RAISE_APPLICATION_ERROR(-20099, 'Table Names Can Not Start With The Letter X'); END IF; END no_xtabs;
  • 54. File the trigger CREATE TABLE ztest ( testcol VARCHAR2(20)); CREATE TABLE xtest ( testcol VARCHAR2(20));
  • 55.
  • 56.
  • 57. Uses/Advantages – To move application logic and business rules into database – This allows more functionality for DBAs to establish vital constraints/rules of applications – Rules managed in some central “place” – Rules automatically enforced by DBMS, no matter which applications later come on line
  • 58. Bad things can happen CREATE TRIGGER Bad-trigger AFTER UPDATE OF price IN Product REFERENCING OLD AS OldTuple NEW AS NewTuple WHEN (NewTuple.price > 50) UPDATE Product SET price = NewTuple.price * 2 WHERE name = NewTuple.name FOR EACH ROW