0% found this document useful (0 votes)
13 views

Unit 6 Database Triggers

Uploaded by

Rakesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit 6 Database Triggers

Uploaded by

Rakesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Unit 6 Database Triggers

Triggers are stored programs that are fired automatically when some events occur. The code to
be fired can be defined as per the requirement.
Oracle has also provided the facility to mention the event upon which the trigger needs to be fire
and the timing of the execution.

A trigger can include SQL and PL/SQL statements to execute as a unit and can invoke
stored procedures. However, procedures and triggers differ in the way that they are
invoked. While a procedure is explicitly executed by a user, application, or trigger,
one or more triggers are implicitly fired (executed) by Oracle when a triggering
INSERT, UPDATE, or DELETE statement is issued, no matter which user is
connected or which application is being used.

For example, Figure shows a database application with some SQL statements that
implicitly fire several triggers stored in the database.

Notice that triggers are stored in the database separately from their associated tables.
Triggers can be defined only on tables, not on views. However, triggers on the base table(s) of a
view are fired if an INSERT, UPDATE, or DELETE statement is issued against a view.
Benefits of Triggers
Following are the benefits of triggers.
 Generating some derived column values automatically
 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions
6.1 Use of Database Trigger
In many cases, triggers supplement the standard capabilities of Oracle to provide a highly
customized database management system. For example, a trigger can permit DML operations
against a table only if they are issued during regular business hours. The standard security
features of Oracle, roles and privileges, govern which users can submit DML statements against
the table. In addition, the trigger further restricts DML operations to occur only at certain times
during weekdays. This is just one way that you can use triggers to customize information
management in an Oracle database.
In addition, triggers are commonly used 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 sophisticated auditing
 maintain synchronous table replicates
 gather statistics on table access
6.2 Database Triggers Vs Procedure
1. We can execute a stored procedure whenever we want with the help of
the exec command, but a trigger can only be executed whenever an event (insert, delete,
and update) is fired on the table on which the trigger is defined.
2. We can call a stored procedure from inside another stored procedure but we can't directly
call another trigger within a trigger. We can only achieve nesting of triggers in which the
action (insert, delete, and update) defined within a trigger can initiate execution of
another trigger defined on the same table or a different table.
3. Stored procedures can be scheduled through a job to execute on a predefined time, but we
can't schedule a trigger.
4. Stored procedure can take input parameters, but we can't pass parameters as input to a
trigger.
5. Stored procedures can return values but a trigger cannot return a value.
6. We can use Print commands inside a stored procedure for debugging purposes but we
can't use print commands inside a trigger.
7. We can use transaction statements like begin transaction, commit transaction, and
rollback inside a stored procedure but we can't use transaction statements inside a trigger.
8. We can call a stored procedure from the front end (.asp files, .aspx files, .ascx files, etc.)
but we can't call a trigger from these files.
9. Stored procedures are used for performing tasks. Stored procedures are normally used for
performing user specified tasks. They can have parameters and return multiple results
sets.
10. The Triggers for auditing work: Triggers normally are used for auditing work. They can
be used to trace the activities of table events.
6.3 Triggers vs. Declarative Integrity Constraints
Triggers and declarative integrity constraints can both be used to constrain data input. However,
triggers and integrity constraints have significant differences.
A declarative integrity constraint is a statement about the database that is never false while the
constraint is enabled. A constraint applies to existing data in the table and any statement that
manipulates the table.
Triggers constrain what transactions can do. A trigger does not apply to data loaded before the
definition of the trigger. Therefore, it does not guarantee all data in a table conforms to its rules.
A trigger enforces transitional constraints; that is, a trigger only enforces a constraint at the time
that the data changes. Therefore, a constraint such as "make sure that the delivery date is at least
seven days from today" should be enforced by a trigger, not a declarative integrity constraint.
Parts of a Trigger
A trigger has three basic parts:
 a triggering event or statement
 a trigger restriction
 a trigger action
Figure 15 - 3 represents each of these parts of a trigger and is not meant to show exact syntax.
Each part of a trigger is explained in greater detail in the following sections.

Figure 15 - 3. The REORDER Trigger


Triggering Event or Statement
A triggering event or statement is the SQL statement that causes a trigger to be fired. A
triggering event can be an INSERT, UPDATE, or DELETE statement on a table.
For example, in Figure 15 - 3, the triggering statement is
. . . UPDATE OF parts_on_hand ON inventory . . .
which means that when the PARTS_ON_HAND column of a row in the INVENTORY table is
updated, fire the trigger. Note that 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. Because
INSERT and DELETE statements affect entire rows of information, a column list cannot be
specified for these options.
A triggering event can specify multiple DML statements, as in
. . . INSERT OR UPDATE OR DELETE OF inventory . . .
which means that when an INSERT, UPDATE, or DELETE statement is issued against the
INVENTORY table, fire the trigger. When multiple types of DML statements can fire a trigger,
conditional predicates can be used to detect the type of triggering statement. Therefore, a single
trigger can be created that executes different code based on the type of statement that fired the
trigger.
Trigger Restriction
A trigger restriction specifies a Boolean (logical) expression that must be TRUE for the trigger to
fire. The trigger action is not executed if the trigger restriction evaluates to FALSE or
UNKNOWN.
A trigger restriction is an option available for triggers that are fired for each row. Its function is
to control the execution of a trigger conditionally. You specify a trigger restriction using a
WHEN clause. For example, the REORDER trigger in Figure 15 - 3 has a trigger restriction. The
trigger is fired by an UPDATE statement affecting the PARTS_ON_HAND column of the
INVENTORY table, but the trigger action only fires if the following expression is TRUE:
new.parts_on_hand < new.reorder_point
Trigger Action
A trigger action is the procedure (PL/SQL block) that contains the SQL statements and PL/SQL
code to be executed when a triggering statement is issued and the trigger restriction evaluates to
TRUE.
Similar to stored procedures, a trigger action can contain SQL and PL/SQL statements, define
PL/SQL language constructs (variables, constants, cursors, exceptions, and so on), and call
stored procedures. Additionally, for row trigger, the statements in a trigger action have access to
column values (new and old) of the current row being processed by the trigger. Two correlation
names provide access to the old and new values for each column.
6.4 Types of Triggers
When you define a trigger, you can specify the number of times the trigger action is to be
executed: once for every row affected by the triggering statement (such as might be fired by an
UPDATE statement that updates many rows), or 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 executed at all.
Row triggers are useful if the code in the trigger action depends on data provided by the
triggering statement or rows that are affected. For example, Figure 15 - 3 illustrates a row trigger
that uses the values of each row affected by the triggering statement.
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, regardless of how many rows are deleted
from the table.
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, if a trigger makes a
complex security check on the current time or user, or if a trigger generates a single audit record
based on the type of triggering statement, a statement trigger is used.
BEFORE vs. AFTER Triggers
When defining a trigger, you can specify the trigger timing. That is, you can specify whether the
trigger action is to be executed before or after the triggering statement. BEFORE and AFTER
apply to both statement and row triggers.
BEFORE Triggers BEFORE triggers execute the trigger action before the triggering statement.
This type of trigger is commonly used in the following situations:
 BEFORE triggers are used when the trigger action should determine whether the
triggering statement should be allowed to complete. By 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.
 BEFORE triggers are used to derive specific column values before completing a
triggering INSERT or UPDATE statement.
AFTER Triggers AFTER triggers execute the trigger action after the triggering statement is
executed. AFTER triggers are used in the following situations:
 AFTER triggers are used when you want the triggering statement to complete before
executing the trigger action.
 If a BEFORE trigger is already present, an AFTER trigger can perform different actions
on the same triggering statement.
Combinations
Using the options listed in the previous two sections, you can create four types of triggers:
 BEFORE statement trigger Before executing the triggering statement, the trigger action
is executed.
 BEFORE row trigger Before modifying each row affected by the triggering statement
and before checking appropriate integrity constraints, the trigger action is executed
provided that the trigger restriction was not violated.
 AFTER statement trigger After executing the triggering statement and applying any
deferred integrity constraints, the trigger action is executed.
 AFTER row trigger After modifying each row affected by the triggering statement and
possibly applying appropriate integrity constraints, the trigger action is executed for the
current row provided the trigger restriction was not violated. Unlike BEFORE row
triggers, AFTER row triggers lock rows.
You can have multiple triggers of the same type for the same statement for any given table. For
example you may have two BEFORE STATEMENT triggers for UPDATE statements on the
EMP table. Multiple triggers of the same type permit modular installation of applications that
have triggers on the same tables. Also, Oracle snapshot logs use AFTER ROW triggers, so you
can design your own AFTER ROW trigger in addition to the Oracle-defined AFTER ROW
trigger.
You can create as many triggers of the preceding different types as you need for each type of
DML statement (INSERT, UPDATE, or DELETE). For example, suppose you have a table,
SAL, and you want to know when the table is being accessed and the types of queries being
issued. Figure 15 - 4 contains a sample package and trigger that tracks this information by hour
and type of action (for example, UPDATE, DELETE, or INSERT) on table SAL. A global
session variable, STAT.ROWCNT, is initialized to zero by a BEFORE statement trigger, then it
is increased each time the row trigger is executed, and finally the statistical information is saved
in the table STAT_TAB by the AFTER statement trigger.
DROP TABLE stat_tab;
CREATE TABLE stat_tab(utype CHAR(8),
rowcnt INTEGER, uhour INTEGER);

CREATE OR REPLACE PACKAGE stat IS


rowcnt INTEGER;
END;
/

CREATE TRIGGER bt BEFORE UPDATE OR DELETE OR INSERT ON sal


BEGIN
stat.rowcnt := 0;
END;
/
CREATE TRIGGER rt BEFORE UPDATE OR DELETE OR INSERT ON sal
FOR EACH ROW BEGIN
stat.rowcnt := stat.rowcnt + 1;
END;
/

CREATE TRIGGER at AFTER UPDATE OR DELETE OR INSERT ON sal


DECLARE
typ CHAR(8);
hour NUMBER;
BEGIN
IF updating
THEN typ := 'update'; END IF;
IF deleting THEN typ := 'delete'; END IF;
IF inserting THEN typ := 'insert'; END IF;
hour := TRUNC((SYSDATE - TRUNC(SYSDATE)) * 24);
UPDATE stat_tab
SET rowcnt = rowcnt + stat.rowcnt
WHERE utype = typ
AND uhour = hour;
IF SQL%ROWCOUNT = 0 THEN
INSERT INTO stat_tab VALUES (typ, stat.rowcnt, hour);
END IF;
EXCEPTION
WHEN dup_val_on_index THEN
UPDATE stat_tab
SET rowcnt = rowcnt + stat.rowcnt
WHERE utype = typ
AND uhour = hour;
END;
/
Figure 15 - 4. Sample Package and Trigger for SAL Table
6.5 Deleting Trigger
Once you have created a trigger in Oracle, you might find that you need to remove it from the
database. You can do this with the DROP TRIGGER statement.
Syntax
The syntax to a drop a trigger in Oracle in Oracle/PLSQL is:
DROP TRIGGER trigger_name;
Parameters or Arguments
trigger_name
The name of the trigger that you wish to drop.
Example
Let's look at an example of how to drop a trigger in Oracle.
For example:
DROP TRIGGER orders_before_insert;

Disable a Trigger
Syntax
The syntax for a disabling a Trigger in Oracle/PLSQL is:
ALTER TRIGGER trigger_name DISABLE;
For example:
ALTER TRIGGER orders_before_insert DISABLE;
Disable all Triggers on a table
Syntax
The syntax for a disabling all Triggers on a table in Oracle/PLSQL is:
ALTER TABLE table_name DISABLE ALL TRIGGERS;

For example:
ALTER TABLE orders DISABLE ALL TRIGGERS;

Enable a Trigger
Syntax
The syntax for a enabling a Trigger in Oracle/PLSQL is:
ALTER TRIGGER trigger_name ENABLE;
For example:
ALTER TRIGGER orders_before_insert ENABLE;

Enable all Triggers on a table


Syntax
The syntax to enable all triggers on a table in Oracle/PLSQL is:
ALTER TABLE table_name ENABLE ALL TRIGGERS;
For example:
ALTER TABLE orders ENABLE ALL TRIGGERS;
6.6 Generation of Primary Key Using Database Trigger
It is possible to automatically generate a primary key for Oracle Database tables when they are
created. The steps below will show how to configure database tables so that primary keys are
automatically generated:
The following example would create an automatic primary key generation with the following
table:
1. Create Table with primary key and any additional attributes.
create table test (id number, testdata varchar2(255));
2. Create Sequence
create sequence test_seq
start with 1
increment by 1
nomaxvalue;
3. Create Trigger
create trigger test_trigger
before insert on test
for each row
begin
select test_seq.nextval into :new.id from dual;
end;
/
4. Test
insert into test values(‘hello world!’);
commit;
select * from test;

You might also like