0% found this document useful (0 votes)
7 views20 pages

Chapitre 1 - Triggers

Uploaded by

departechnost21
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)
7 views20 pages

Chapitre 1 - Triggers

Uploaded by

departechnost21
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/ 20

Chapter 1 (2 ndPart): Triggers

on Firebird RDBMS
Databases

M. Laïdi FOUGHALI Révision 29/10/2019 6h46


Plan
 About triggers
 The advantages of using triggers
 Triggers language
 SET TERM
 The trigger header remarks
 NEW and OLD context variables
 Generators
 Alter/Drop triggers
 Triggers and transactions
 Exceptions
About triggers
 A trigger is a self-contained routine associated with a table or
view that automatically performs an action when a row in the
table or view is inserted, updated, or deleted.
 A trigger is never called directly. Instead, when an application or
user attempts to INSERT, UPDATE, or DELETE a row in a table, any
triggers associated with that table and operation are
automatically executed, or fired.
 Triggers can make use of exceptions, named messages called
for error handling. When an exception is raised by a trigger, it
returns an error message, terminates the trigger, and undoes any
changes made by the trigger, unless the exception is handled
with a WHEN statement in the trigger.
The advantages of using triggers
 Automatic enforcement of data restrictions, to make sure
users enter only valid values into columns.
 Reduced application maintenance, since changes to a
trigger are automatically reflected in all applications that use
the associated table without the need to recompile and
relink.
 Automatic logging of changes to tables. An application can
keep a running log of changes with a trigger that fires
whenever a table is modified.
 Automatic notification of changes to the database with
event alerters in triggers.
Creating triggers
CREATE TRIGGER name FOR {table | view}
[ACTIVE | INACTIVE]
{BEFORE | AFTER} {DELETE | INSERT | UPDATE}
[POSITION number]
AS <trigger_body>
<trigger_body> = [<variable_declaration_list>] <block>
<variable_declaration_list> =DECLARE VARIABLE variable datatype;
[DECLARE VARIABLE variable datatype; …]
<block> =
BEGIN
<compound_statement> [<compound_statement> …]
END
<compound_statement> = {<block> | statement;}
Triggers language (1/3)
Statement Description
BEGIN … END Defines a block of statements that executes as one. The
BEGIN keyword starts the block; the END keyword
terminates it. Neither should be followed by a semicolon.
variable = expression Assignment statement which assigns the value of
expression to local variable, variable.
/* comment_text */ Programmer’s comment, where comment_text can be any
number of lines of text.
EXCEPTION exception_name Raises the named exception. An exception is a user-
defined error, which returns an error message to the calling
application unless handled by a WHEN statement.
EXECUTE PROCEDURE Executes stored procedure, proc_name, with the listed
proc_name [var [, var …]] input arguments, returning values in the listed output
[RETURNING_VALUES arguments. Input and output arguments must be local
var [, var …]] variables.
Triggers language (2/3)
Statement Description
FOR select_statement Repeats the statement or block following DO for every
DO compound_statement qualifying row retrieved by select_statement.
select_statement: a normal SELECT statement, except the
INTO clause is required and must come last.
compound_statement Either a single statement in procedure and trigger
language or a block of statements bracketed by BEGIN
and END.
IF (condition) Tests condition, and if it is TRUE, performs the statement or
THEN compound_statement block following THEN, otherwise performs the statement or
[ELSE compound_statement] block following ELSE, if present.

condition: a Boolean expression (TRUE, FALSE, or


UNKNOWN), generally two expressions as operands of a
comparison operator.
Triggers language (3/3)
Statement Description
NEW.column New context variable that indicates a new column value in
an INSERT or UPDATE operation.
OLD.column Old context variable that indicates a column value before
an UPDATE or DELETE operation.
POST_EVENT event_name Posts the event, event_name.
WHILE (condition) While condition is TRUE, keep performing
DO compound_statement compound_statement. First condition is tested, and if it is
TRUE,
then compound_statement is performed. This sequence is
repeated until condition is no longer TRUE.
WHEN {error [, error …]|ANY} Error-handling statement. When one of the specified errors
DO compound_statement occurs, performs compound_statement. WHEN statements,
if present, must come at the end of a block, just before
END.
error: EXCEPTION exception_name, SQLCODE errcode or
GDSCODE number.
ANY: handles any errors.
SET TERM
Because each statement in a trigger body must be terminated by
a semicolon, you must define a different symbol to terminate the
trigger body itself.
Example of using of !! as terminator block :
SET TERM !! ;
CREATE TRIGGER SIMPLE FOR EMPLOYEE
AFTER UPDATE AS
BEGIN

END !!
SET TERM ; !!
The trigger header
 The trigger status, ACTIVE or INACTIVE, determines whether a
trigger is activated when the specified operation occurs. ACTIVE
is the default, meaning the trigger fires when the operation
occurs. Setting status to INACTIVE with ALTER TRIGGER is useful
when developing and testing applications and triggers.
 The optional sequence indicator, POSITION number, specifies the
order in which the trigger fires in relation to other triggers on the
same table and event. number can be any integer between
zero and 32,767. The default is zero. Lower-numbered triggers fire
first.
 Multiple triggers can have the same position number; they will
fire in random order.
The trigger header remarks
 The trigger status, ACTIVE or INACTIVE, determines whether a
trigger is activated when the specified operation occurs. ACTIVE
is the default, meaning the trigger fires when the operation
occurs. Setting status to INACTIVE with ALTER TRIGGER is useful
when developing and testing applications and triggers.
 The optional sequence indicator, POSITION number, specifies the
order in which the trigger fires in relation to other triggers on the
same table and event. number can be any integer between
zero and 32,767. The default is zero. Lower-numbered triggers fire
first.
 Multiple triggers can have the same position number; they will
fire in random order.
NEW and OLD context variables
 The OLD context variable refers to the current or previous values
in a row being updated or deleted. OLD is not used for inserts.
NEW refers to a new set of INSERT or UPDATE values for a row.
NEW is not used for deletes.
 The syntax for context variables is as follows:
NEW.column
OLD.column
where column is any column in the affected row. Context
variables can be used anywhere a regular variable can be
used.
 New values for a row can only be altered before actions
Generators (1/2)
 A generator is a database object that automatically increments
each time the special function, GEN_ID(), is called.
 Generators cannot be used in read-only databases.
 GEN_ID() can be used in a statement anywhere that a variable
can be used. Generators are typically used to ensure that a
number inserted into a column is unique, or in sequential order.
Generators are particularly useful in triggers for inserting unique
column values.
 Use the CREATE GENERATOR statement the create a generator
and SET GENERATOR to initialize it.
 The syntax for using GEN_ID() in a SQL statement is:
GEN_ID(gen_name, step)
Generators (2/2)
 The following trigger uses GEN_ID() to increment a new customer
number before values are inserted into the CUSTOMER table:
SET TERM !! ;
CREATE TRIGGER SET_CUST_NO FOR CUSTOMER
BEFORE INSERT AS
BEGIN
NEW.CUST_NO = GEN_ID(CUST_NO_GEN, 1);
END !!
SET TERM ; !!
 Note This trigger must be defined to fire before the insert, since it
assigns values to NEW.CUST_NO.
Altering triggers / Dropping triggers

See exercises
Triggers and transactions
The importants things to considerate are:
 Triggers operate within the context of the transaction in the
program where they are fired. Triggers are considered part of the
calling program’s current unit of work.
 If triggers are fired in a transaction, and the transaction is rolled
back, then any actions performed by the triggers are also rolled
back.
Exceptions
 An exception is a named error message that can be raised
from a trigger or a stored procedure.
 When raised in a trigger, an exception returns an error
message to the calling program and terminates the trigger,
unless the exception is handled by a WHEN statement in the
trigger.
 Like procedures and triggers, exceptions are created and
stored in a database, where they can be used by any
procedure or trigger in the database. Exceptions must be
created and committed before they can be used in
triggers.
Exceptions (1/2)
 An exception is a named error message that can be raised from
a trigger or a stored procedure.
 When raised in a trigger, an exception returns an error message
to the calling program and terminates the trigger, unless the
exception is handled by a WHEN statement in the trigger.
 Like procedures and triggers, exceptions are created and stored
in a database, where they can be used by any procedure or
trigger in the database. Exceptions must be created and
committed before they can be used in triggers.
 To raise an existing exception in a trigger, use the following
syntax: EXCEPTION name;
Exceptions (2/2)
For example, suppose an exception is created as follows:
CREATE EXCEPTION RAISE_TOO_HIGH 'New salary exceeds old by more than 50%.;

The trigger, SAVE_SALARY_CHANGE, might raise the exception as


follows:
SET TERM !! ;
CREATE TRIGGER SAVE_SALARY_CHANGE FOR EMPLOYEE AFTER UPDATE AS
DECLARE VARIABLE PCNT_RAISE;
BEGIN
PCNT_RAISE = (NEW.SALARY - OLD.SALARY) * 100 / OLD.SALARY;
IF (OLD.SALARY <> NEW.SALARY) THEN
IF (PCNT_RAISE > 50) THEN EXCEPTION RAISE_TOO_HIGH;
ELSE
BEGIN
INSERT INTO SALARY_HISTORY (EMP_NO, CHANGE_DATE, UPDATER_ID, OLD_SALARY,
PERCENT_CHANGE)
VALUES (OLD.EMP_NO, 'NOW', USER, OLD.SALARY, PCNT_RAISE);
END
END !!
SET TERM ; !!
Questions ?

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy