Professional Documents
Culture Documents
DB2 9.5 SQL Procedure Developer Exam 735 Prep, Part 4:: Triggers
DB2 9.5 SQL Procedure Developer Exam 735 Prep, Part 4:: Triggers
26 Feb 2009
Gain an understanding of the fundamental concepts behind IBM DB2 triggers
when, how, and what kind of triggers can be used under various circumstances and
the required user privileges. This tutorial is Part 4 of a series of tutorials designed to
help you prepare for the IBM Certified Solution Developer - DB2 9.5 SQL Procedure
Developer exam (Exam 735).
Triggers
Copyright IBM Corporation 2008. All rights reserved.
Page 1 of 13
developerWorks
ibm.com/developerWorks
rely on these tutorials as your only preparation for the exam. More exam resources
can be found in the Resources section of this tutorial.
Objectives
After completing this tutorial, you should :
Be able to identify proper usage of triggers
Understand trigger types
Understand the required privileges for creating a trigger
Know how to create a trigger
Be able to create, deploy and identify trigger actions
Be familiar with advanced uses for triggers
Prerequisites
To take the DB2 9.5 SQL Procedure Developer exam, you must have already
passed the DB2 9 Family Fundamentals exam (Exam 730). You can use the DB2 9
Fundamentals certification 730 prep series to prepare for that exam. It is a very
popular series that has helped many people understand the fundamentals of the
DB2 family of products.
This tutorial is written for DB2 programmers whose skills and experience are at an
introductory to intermediate level. You should have a general background knowledge
of how a relational database works as well as basic knowledge of databases,
database programming constructs, and operating system security. You should also
be familiar with using the DB2 Command Line Processor (CLP), and you should
have a working knowledge of SQL.
System requirements
To run the examples in this tutorial, you need access to a DB2 9.5 database server
and the SAMPLE database that is provided with DB2. (The SAMPLE database can
Triggers
Page 2 of 13
ibm.com/developerWorks
developerWorks
be created by executing the command db2sampl from the DB2 Command Line
Processor.)
Trigger types
BEFORE triggers: These are executed before a database insert or
update is applied against a table. CALL and SIGNAL are two SQL
statements allowed.
BEFORE DELETE triggers: Executed before a delete operation.
AFTER triggers:Executed after an update, insert, or delete operation.
These are used to update data in other tables that would then reflect the
relationship and consistency between the tables, and to also ensure data
integrity. AFTER triggers are often used to generate alerts to users under
specific circumstances.
INSTEAD OF triggers: These enable the execution of insert, update and
Triggers
Copyright IBM Corporation 2008. All rights reserved.
Page 3 of 13
developerWorks
ibm.com/developerWorks
Triggers
Page 4 of 13
ibm.com/developerWorks
developerWorks
UNIX, and Windows Information Center, in the section "Create Trigger" statement
for details on CREATE TRIGGER authorizations (see Resources). Listing 1 shows
you the basic syntax used to create a trigger:
Listing 1. General syntax diagram for CREATE TRIGGER statement
.-NO CASCADE-.
>>-CREATE TRIGGER--trigger-name--+-+------------+--BEFORE-+----->
+-AFTER------------------+
'-INSTEAD OF-------------'
>--+-INSERT--------------------------+--ON--+-table-name-+------>
+-DELETE--------------------------+
'-view-name--'
'-UPDATE--+---------------------+-'
|
.-,-----------. |
|
V
| |
'-OF----column-name-+-'
>--+------------------------------------------------------------------+-->
|
.-------------------------------------------------. |
|
V (1)
(2)
.-AS-.
| |
'-REFERENCING------------------+-OLD--+----+--correlation-name-+-+-'
|
.-AS-.
|
+-NEW--+----+--correlation-name-+
|
.-AS-.
|
+-OLD TABLE--+----+--identifier-+
|
.-AS-.
|
'-NEW TABLE--+----+--identifier-'
>--+-FOR EACH ROW--------------+--| triggered-action |--------->
| (3)
|
'--------FOR EACH STATEMENT-'
triggered-action
|--+-------------------------------------+---------------------->
| (4)
|
'--------WHEN--(--search-condition--)-'
In order to understand the syntax diagram in Listing 1, let's create several simple
triggers that demonstrate the basic syntax of the CREATE TRIGGER statement. A
trigger has three main components:
Trigger event
Trigger condition
Trigger action
Find an explanation of each of these components with the following examples.
Listing 2 shows the syntax for an AFTER INSERT trigger. INSERT is one of the
trigger events. This trigger is activated (fired) when rows are inserted into the base
table employee. Because this is defined as an AFTER trigger, the timing condition is
performed after an INSERT statement on employee table. The trigger action is to
insert an audit entry into the audit_emp base table. REFERENCING NEW AS
Triggers
Copyright IBM Corporation 2008. All rights reserved.
Page 5 of 13
developerWorks
ibm.com/developerWorks
provides a correlation name that specifies the prefix you assign to allow for
referencing the new values of columns affected by the trigger. FOR EACH ROW is
another timing condition. The trigger actions are executed for each row the trigger
event processes, hence, if the INSERT statement processes 25 rows, the audit_emp
table is inserted with 25 new audit entries. Listing 2 shows the syntax for this trigger.
Listing 2. A simple AFTER INSERT trigger
CREATE TRIGGER new_emp
AFTER INSERT ON employee
REFERENCING NEW AS n
FOR EACH ROW
INSERT INTO audit_emp VALUES (n.empno, 'Insert',0.0, current user, current timestamp)
Listing 3 shows the syntax for the AFTER DELETE trigger. Delete is one of the
trigger events. This trigger is activated (fired) when rows are deleted from the base
table employee. Because this is defined as an AFTER trigger, the timing condition is
performed after a DELETE statement on employee table. The trigger action is to
insert an audit entry into the audit_emp base table. REFERENCING OLD AS
provides a correlation name that specifies the prefix you assign to allow for
referencing the old values of columns affected by the trigger. FOR EACH ROW is
another timing condition. The trigger actions are executed for each row the trigger
event processes, hence, if the DELETE statement processes five rows, the
audit_emp table is inserted with five new audit entries.
Listing 3. A simple AFTER DELETE trigger
CREATE TRIGGER purge_emp
AFTER DELETE ON employee
REFERENCING OLD AS o
FOR EACH ROW
INSERT INTO audit_emp VALUES (o.empno, 'Delete',0.0, current user, current timestamp)
Listing 4 shows the syntax for the AFTER UPDATE trigger. Update is one of the
trigger events. This trigger is activated (fired) when updates are performed on the
base table employee. Because this is defined as an AFTER trigger, the timing
condition is performed after an UPDATE statement on employee table. The trigger
action is to insert an audit entry into the audit_emp base table. REFERENCING OLD
AS provides a correlation name that specifies the prefix you assign to allow for
referencing the old values of columns affected by the trigger, as does the
REFERENCING NEW clause. FOR EACH ROW is another timing condition. The trigger
actions are executed for each row the trigger event processes, hence, if the UPDATE
statement processes 100 rows, the audit_emp table is inserted with 100 new audit
entries. The WHEN clause in the trigger body provides for conditional logic to be
included within the FOR EACH ROW. This provides for the trigger action to be
conditional on the results of a test you define using the correlation names declared
in the REFERENCE clause. This example compare the existing employee.salary
Triggers
Page 6 of 13
ibm.com/developerWorks
developerWorks
column in the base table employee to a newly updated value from the UPDATE
statement. If the condition is true (not equal), you then perform the INSERT
statement on the audit_emp table using the newly updated value from the UPDATE
statement on the employee table.
Listing 4. A simple AFTER UPDATE trigger
CREATE TRIGGER update_emp
AFTER UPDATE OF salary ON employee
REFERENCING OLD AS o NEW AS n
FOR EACH ROW
WHEN (n.salary <> o.salry)
INSERT INTO audit_emp VALUES (o.empno,'Update',n.salary,current user, current timestamp)
Listing 5 shows the syntax for the BEFORE UPDATE trigger. Again, update is one of
the trigger events. This trigger is activated (fired) when updates are performed on
the base table employee. Because this is defined as a BEFORE trigger, the timing
condition is performed before an UPDATE statement on the employee table. The
trigger action sets the employee.salary to 75,000.00 if the newly updated value for
salary table is equal to 60,000.00. REFERENCING OLD AS provides a correlation
name that specifies the prefix you assign to allow for referencing the old values of
columns affected by the trigger, as does the REFERENCING NEW clause. FOR EACH
ROW is another timing condition. The WHEN clause in the trigger body provides for
conditional logic to be included within the FOR EACH ROW. This provides for the
trigger action to be conditional based on the results of a test you define using the
correlation names declared in the REFERENCE clause. This example compares the
updated value in the UPDATE statement (employee.salary). If it is equal to
60,000.00, you set the salary to 75,000.00.
Listing 5. A simple BEFORE UPDATE trigger
CREATE TRIGGER update_bemp
BEFORE UPDATE ON employee
REFERENCING OLD AS o NEW AS n
FOR EACH ROW
WHEN (n.salary = 60000.00)
SET n.salary = 75000.00)
Triggers
Copyright IBM Corporation 2008. All rights reserved.
Page 7 of 13
developerWorks
ibm.com/developerWorks
INSTEAD OF triggers
INSTEAD OF triggers are always created for views, never for base tables or
nicknames. By using INSTEAD OF triggers, view modifications are replaced by
trigger logic that functions on behalf of a previously defined view and are transparent
to the calling application.
Listing 6 shows how to create an INSTEAD OF trigger:
Listing 6. Create INSTEAD OF trigger
-- Base Table (employees)
CREATE TABLE "DB2INST1"."EMPLOYEES"
(
"EMPNO"
CHAR(6) NOT NULL
"FIRSTNME" VARCHAR(12) NOT NULL
"LASTNAME" VARCHAR(15) NOT NULL
"PHONENO" CHAR(4)
"SALARY"
DECIMAL(9,2)
)
,
,
,
,
An INSTEAD OF trigger allows for inserting data into the protected column salary in
the employees table. This trigger is activated (fired) when rows are inserted into the
view employeev. Because this is defined as an INSTEAD OF trigger, the timing
condition is performed after an INSERT statement on the view. The trigger action
performs an INSERT in the base table (employees). REFERENCING NEW AS
provides a correlation name that specifies the prefix you assign to allow for
referencing the new values of columns affected by the trigger. FOR EACH ROW is
another timing condition. The trigger actions are executed for each row the trigger
event processes, hence, if the INSERT statement processes five rows, the base
table (employees) is inserted with five new entries and provides a default value of
zero for the salary column not visible from the employeev view.
Triggers
Page 8 of 13
ibm.com/developerWorks
developerWorks
Triggers
Copyright IBM Corporation 2008. All rights reserved.
Page 9 of 13
developerWorks
ibm.com/developerWorks
| |
V
| |
|
| '-WITH----common-table-expression-+-'
|
+-GET DIAGNOSTICS-----------------------------------+
+-IF------------------------------------------------+
+-INSERT--------------------------------------------+
+-ITERATE-------------------------------------------+
+-LEAVE---------------------------------------------+
+-MERGE---------------------------------------------+
+-searched-delete-----------------------------------+
+-searched-update-----------------------------------+
+-SET Variable--------------------------------------+
+-SIGNAL--------------------------------------------+
'-WHILE---------------------------------------------'
Listing 9 illustrates how you can embed a CALL statement from within the trigger
body, invoking a stored procedure. In this example, the parameters are passed by
value to the called procedure write_audit. This simple example demonstrates the
value of invoking stored procedures from a trigger. You should now be able to
extend the trigger body and implement more complex logic using SQL PL
statements.
Listing 9. Invoking a stored procedure from within a trigger
CREATE PROCEDURE write_audit( IN p_empno
IN p_txt
IN p_salary
IN p_user
IN p_curtime
BEGIN
INSERT INTO audit_emp VALUES ( p_empno,
END
CHAR(6),
CHAR(6),
DECIMAL(9,2),
CHAR(8),
TIMESTAMP )
p_txt, p_salary, p_user, p_curtime )
Listing 10 illustrates how you can enforce business rules on data being inserted into
the database. This example establishes business rules for the empprojact table. The
example references the emendate column and enforces several business rules on
the data being inserted into the database. It also assigns the SQLSTATE the value
of 90000 to Business Rule Two. This allows you to force the invocation of a handler.
The SIGNAL statement allows you to force an error or warning through the setting of
SQLSTATE.
Listing 10. BEFORE INSERT trigger Using SQL PL
CREATE TRIGGER business_rules
BEFORE INSERT ON empprojact
REFERENCING NEW AS n
FOR EACH ROW
BEGIN ATOMIC
-- Business Rule One (Project ending date Can't be NULL)
IF (n.emendate IS NULL) THEN
Triggers
Page 10 of 13
ibm.com/developerWorks
developerWorks
Section 4. Conclusion
This tutorial gave an overview of how triggers are created and how, why, and when
they are applied to address various business rules and requirements. This should
now give you a solid base understanding of triggers that is key in preparing for the
IBM Certified Solution Developer - DB2 9.5 SQL Procedure Developer exam (Exam
735).
Triggers
Copyright IBM Corporation 2008. All rights reserved.
Page 11 of 13
developerWorks
ibm.com/developerWorks
Resources
Learn
DB2 9.5 SQL Procedure Developer exam 735 prep series: Get more from this
series of tutorials designed to help you prepare for the IBM Certified Solution
Developer - DB2 9.5 SQL Procedure Developer exam (Exam 735).
"DB2 Basics: Creating Your First Trigger in DB2 Universal Database"
(developerWorks, August 2003): Explore the world of triggers, and see how
they can be used to enforce business rules in your database. This article walks
you through the process of creating a trigger used in a mock banking scenario.
"Enforcing Business Logic using DB2 Triggers, Java UDFs, and the JavaMail
API" (developerWorks, May 2002): Learn about the concept of cause and effect
as implemented in a database application that brings together the concepts of
DB2 triggers, Java user-defined functions (UDFs), and the JavaMail API. The
article example scenario uses a trigger to automatically send customized e-mail
when customers near their credit limits.
DB2 9.5 Linux, UNIX, and Windows Information Center: Find information
describing how to use the DB2 family of products and features, as well as
related WebSphere Information Integration products and features.
DB2 skill kit: Increase your knowledge and skills whether you are a database
administrator or an application developer. Learn how to install, configure, and
administer IBM DB2 Universal Database. Topics covered include: Overview,
installation, configuration, database creation, and administration.
developerWorks resource page for DB2 for Linux, UNIX, and Windows: Find
articles and tutorials, and connect to other resources to expand your DB2 skills.
developerWorks Information Management zone: Learn more about Information
Management. Find technical documentation, how-to articles, education,
downloads, product information, and more.
Stay current with developerWorks technical events and webcasts.
Technology bookstore: Browse for books on these and other technical topics.
Get products and technologies
DB2 Express-C: Now you can use DB2 for free. Download DB2 Express-C, a
free version of DB2 Express Edition for the community that offers the same core
data features as DB2 Express Edition and provides a solid base to build and
deploy applications.
Build your next development project with IBM trial software, available for
download directly from developerWorks.
Triggers
Page 12 of 13
ibm.com/developerWorks
developerWorks
Discuss
Participate in the discussion forum for this content.
Participate in developerWorks blogs and get involved in the developerWorks
community.
James Merry
James Merry is an enablement consultant working with IBM Business Partners to
help them enable their applications to DB2. He most recently was a member of the
IBM Content Management eMail Compliance team. He has been working in the
relational database industry for over 20 years developing database applications and
database administration.
Triggers
Copyright IBM Corporation 2008. All rights reserved.
Page 13 of 13