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

Triggers in Firebird

Triggers are stored procedures that are automatically executed when data is inserted, updated, or deleted from a table or view. They allow for automatic enforcement of business rules and logging of data changes. Triggers differ from stored procedures in that triggers can access old and new field values using context variables and do not have input or output parameters.

Uploaded by

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

Triggers in Firebird

Triggers are stored procedures that are automatically executed when data is inserted, updated, or deleted from a table or view. They allow for automatic enforcement of business rules and logging of data changes. Triggers differ from stored procedures in that triggers can access old and new field values using context variables and do not have input or output parameters.

Uploaded by

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

Triggers in Firebird

General
 Triggers are self-contained routines (special Stored Procedures), which are
connected to a table or view
 A trigger is automatically executed ("fired") when a record is inserted, updated or
deleted from a table/view
 Triggers are never called directly but only through one of the commands
INSERT, UPDATE or DELETE
 Triggers are written in Stored Procedure and Trigger Language and can use
Exceptions

Advantages
 Automatic enforcement of conditions and limitations for the contents
 Reduced maintenance for the applications
 You can implement a modification logging mechanism for tables
 Generators can be called automatically and their values assigned to fields
 Automatic notification of applications by calling of Events
 Automatic upper-casing of fields to enable case-insensitive searching

General Syntax
CREATE [OR ALTER] TRIGGER name FOR tablename
[ACTIVE | INACTIVE]
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
[OR {INSERT | UPDATE | DELETE}
[OR {INSERT | UPDATE | DELETE}]]
[POSITION number]
AS <trigger_body>
 ACTIVE/INACTIVE: A trigger can be deactivated, e.g. for development. Can
also be used with ALTER TRIGGER.
 BEFORE/AFTER: Tells the system if the trigger must be fired before or after the
Insert/Update/Delete operation
 POSITION: Trigger calling order. Triggers with low numbers are fired first.
Triggers with the same position number are fired in an undefined order. The
position defaults to 0.
 trigger_body: Same as body in a Stored Procedure

Differences to Stored Procedures


 Context variables (OLD.colname and NEW.colname) can only be used in triggers
 Triggers do not have in- and/or out-parameters. There is no SUSPEND and no
EXIT.
 NEW.colname: New column value for INSERT or UPDATE operations
 OLD.colname: Old column value for UPDATE or DELETE operations

Context Variables
Variable Name Contents
OLD.field Content of field before insert/update/delete
NEW.field New field content for an insert or update operation
INSERTING True if the trigger is called for an INSERT operation
UPDATING True if the trigger is called for an UPDATE operation
DELETING True if the trigger is called for a DELETE operation

Altering and deleting triggers


 ALTER TRIGGER name ACTIVE | INACTIVE: activate/deactivate a trigger
 ALTER TRIGGER name ...: Change a complete trigger definition
 DROP TRIGGER name: Delete trigger. Can only be performed by the owner of
the trigger. Can not be performed when the trigger is currently running.
 CREATE OR ALTER TRIGGER name ...: Create trigger if it doesn't exist, alter
trigger otherwise

Triggers and Transactions


 Triggers run in the context of their transaction, they are treated as a part of the
current operation
 The actions of a trigger which fired in a transaction which is ROLLBACKed, will
be rolled back, too.

Examples
Insert a Generator value for a newly inserted record
CREATE TRIGGER Create_Log_ID FOR Logs
BEFORE INSERT
AS BEGIN
NEW.ID = GEN_ID (LogIdGenerator, 1);
END;

Log Changes to the PRICE field


CREATE TRIGGER Log_Price_Upd FOR Articles
AFTER INSERT OR UPDATE
AS BEGIN
IF INSERTING THEN
INSERT INTO PRICE_LOGS (ART_ID, ACTION, DATETIME, NEW_PRICE) VALUES
(NEW.ART_ID, 'I', 'NOW', NEW.PRICE);
ELSE
INSERT INTO PRICE_LOGS (ART_ID, ACTION, DATETIME, NEW_PRICE) VALUES
(NEW.ART_ID, 'U', 'NOW', NEW.PRICE);
END;

Case insensitive searching

Suppose you have a table of employees and want to be able to search for employee last
name, independent of case:

CREATE TABLE EMPLOYEES (


EMPNO INTEGER NOT NULL PRIMARY KEY,
LASTNAME VARCHAR (50),
FIRSTNAME VARCHAR (50));

Now include a new field LASTNAME_UPPER which will contain the uppercased
lastname. You will also need a collation so that the UPPER() function can work at all.

CREATE TABLE EMPLOYEES (


EMPNO INTEGER NOT NULL PRIMARY KEY,
LASTNAME VARCHAR (50) COLLATE DE_DE,
LASTNAME_UPPER VARCHAR (50) COLLATE DE_DE,
FIRSTNAME VARCHAR (50) COLLATE DE_DE);

Now you need a trigger which will fill the LASTNAME_UPPER field at every INSERT
or UPDATE operation. There is no need for your application to fill
LASTNAME_UPPER.

CREATE OR ALTER TRIGGER BIU_EMPLOYEES


FOR EMPLOYEES
BEFORE INSERT OR UPDATE AS
BEGIN
NEW.LASTNAME_UPPER = UPPER (NEW.LASTNAME);
END;

Next you need an index on the LASTNAME_UPPER field so that searching is fast:

CREATE INDEX IDX_EMPL_LASTNAME ON EMPLOYEES (LASTNAME_UPPER);

Now you can search for employees using a normal SELECT and by using
LASTNAME_UPPER instead of LASTNAME. Remember to uppercase the term you are
searching for:

SELECT EMPNO FROM EMPLOYEES WHERE LASTNAME_UPPER = 'HEYMANN';


Stored Procedures in Firebird
General
 "Stored Procedures" are routines which run on the server and can be called by
client applications
 Stored Procedures are pre-compiled. So they don't need to be sent over the
network and parsed every time. They're just executed.
 Procedures can take parameters and – like SELECT – give back their data in the
form of a table.

Advantages
 Parts of code only implemented once: client applications get smaller and less
complicated to implement and mantain.
 Easier Maintenance: Client applications don't need to be recompiled and
redistributed
 Increased performance because of reduced network traffic

Calling Stored Procedures


 Stored Procedures can perform an action and do not return any data
 "Select" Procedures return tables, just like SELECT, Tables or Views. They can
be used like a table reference in a SELECT statement:
SELECT a, b FROM procedurename (params) ...
 To be able to call a procedure, the user must have EXECUTE rights (granted by
GRANT/REVOKE)

Declaring Stored Procedures


CREATE PROCEDURE name [(param1 datatype1, param2 datatype2, ...)]
[RETURNS (param3 datatype3, param4 datatype4, ...)]
AS BEGIN
<body>
END;

Syntax of a variable declaration


DECLARE VARIABLE variable datatype

(In and Out parameters of a Stored Procedure are used like variables)

SET TERM
Every command in a script must be terminated by a semi-colon, the procedure itself, too.
To distinguish the semi-colons in the procedure from the terminating semi-colon, there
must be another terminator for the end of the procedure. This is done with SET TERM:

SET TERM !! ;
CREATE PROCEDURE x AS BEGIN ... END !!
SET TERM ; !!

The first "SET TERM" replaces the terminator semi-colon with the terminator double-
exclamation. The procedure declaration contains the usual semi-colons after each
command. The procedure itself is terminated by the "new" terminator !!. After that, the
terminator symbol is set back to a semi-colon.

Creating, altering and dropping Stored Procedures


 Create: CREATE PROCEDURE name ...
 Alter: ALTER PROCEDURE name ... (the rest is like CREATE PROCEDURE)
 Create or Alter, depending on existance of proceudure: CREATE OR ALTER ...
 Drop: DROP PROCEDURE name. Can only be done by the owner of the
procedure.
You can only drop procedures, which are not used by other procedures, triggers or
views.

Exceptions
 Create: CREATE EXCEPTION name “message“
 Alter: ALTER EXCEPTION name “message“
 Drop: DROP EXCEPTION name

Examples
/* --- Returning a single value –----------------------------------- */
CREATE PROCEDURE Mul (a INTEGER, b INTEGER)
RETURNS (Result INTEGER)
AS BEGIN
Result = a * b;
END

/* --- Returning a table –--------------------------------- */


CREATE PROCEDURE CountTo10
RETURNS (Cnt INTEGER)
AS BEGIN
Cnt = 1;
WHILE (Cnt <= 10) DO BEGIN
SUSPEND; /* Return next line */
Cnt = Cnt + 1;
END;
END
Commands
Command Description Version
BEGIN <statements> END Compound Statement like in PASCAL
variable = expression
Assignment. "variable" can be a local variable,
an "in" or an "out" parameter.
compound_statement A single command or a BEGIN/END block
Normal SELECT statement. The INTO clause
must be present at the end of the statement.
Variable names can be used with a colon
select_statement
preceding them. Example
SELECT PRICE FROM ARTICLES
WHERE ARTNO = :ArticleNo
INTO :EPrice
/* Comment */ Comment, like in C
-- Comment Single line SQL comment 1.5.0
DECLARE VARIABLE name Variable declaration. After AS, before the first 1.5.0
datatype [= startval] BEGIN. (startval)
Re-fire the current exception. Only makes sense
EXCEPTION 1.5.0
in WHEN clause
EXCEPTION name Fire the specified exception. Can be handled 1.5.0
[message] with WHEN. (message)
EXECUTE PROCEDURE name
arg, arg Calling a procedure. arg's must be local
RETURNING_VALUES arg, variables. Nesting and recursion allowed.
arg
EXIT Leaves the procedure (like in PASCAL)
FOR select_statement DO Executes "compound_statement" for every line
compound_statement that is returned by the SELECT statement
IF (condition)
THEN
compound_statement IF statement, like in PASCAL
[ELSE
compound_statement]
POST_EVENT name Posts the specified event
Only for SELECT procedures which return
SUSPEND tables: Waits for the client to request the next
line. Returns the next line to the client.
WHILE (condition) DO
compound_statement WHILE statement. Like in PASCAL.
WHEN {EXCEPTION a | Exception handling. WHEN statements must be
SQLCODE x | ANY} DO at the end of the procedure, directly before the
compound_statement final END.
EXECUTE STATEMENT
stringvalue Executes the DML statement in stringvalue 1.5.0
EXECUTE STATEMENT Executes Statement and returns variables 1.5.0
stringvalue
(singleton)
INTO variable_list
FOR EXECUTE STATEMENT
stringvalue Executes Statement and iterates through the
INTO variable_list DO 1.5.0
resulting lines
compound_statement

Stefan Heymann, 2004-08-22

You might also like