SQL Reference
The CREATE TRIGGER statement defines a trigger in the database.
Invocation
This statement can be embedded in an application program or issued through
the use of dynamic SQL statements. It is an executable statement that
can be dynamically prepared. However, if the bind option DYNAMICRULES
BIND applies, the statement cannot be dynamically prepared (SQLSTATE
42509).
Authorization
The privileges held by the authorization ID of the statement when the
trigger is created must include at least one of the following:
- SYSADM or DBADM authority.
- ALTER privilege on the table on which the trigger is defined, or ALTERIN
privilege on the schema of the table on which the trigger is defined and one
of:
- IMPLICIT_SCHEMA authority on the database, if the implicit or explicit
schema name of the trigger does not exist
- CREATEIN privilege on the schema, if the schema name of the trigger refers
to an existing schema.
If the authorization ID of the statement does not have SYSADM or DBADM
authority, the privileges that the authorization ID of the statement holds
(without considering PUBLIC or group privileges) must include all of the
following as long as the trigger exists:
- SELECT privilege on the table on which the trigger is defined, if any
transition variables or tables are specified
- SELECT privilege on any table or view referenced in the triggered action
condition
- Necessary privileges to invoke the triggered SQL statements
specified.
If a trigger definer can only create the trigger because the definer has
SYSADM authority, then the definer is granted explicit DBADM authority for the
purpose of creating the trigger.
Syntax
>>-CREATE TRIGGER--trigger-name----+-NO CASCADE BEFORE-+-------->
'-AFTER-------------'
>-----+-INSERT-----------------------------+--ON--table-name---->
+-DELETE-----------------------------+
'-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---------------+--MODE DB2SQL--------------->
| (3) |
'--------FOR EACH STATEMENT--'
>-----| triggered-action |-------------------------------------><
triggered-action
|--+-------------------------------+---------------------------->
'-WHEN--(--search-condition--)--'
>-----+-triggered-SQL-statement--------------------------------+-|
| .-------------------------------. |
| V | |
'-BEGIN ATOMIC-----triggered-SQL-statement--;---+---END--'
Notes:
- OLD and NEW may only be specified once each.
- OLD_TABLE and NEW_TABLE may only be specified once each and only for AFTER
triggers.
- FOR EACH STATEMENT may not be specified for BEFORE triggers.
Description
- trigger-name
- Names the trigger. The name, including the implicit or explicit
schema name must not identify a trigger already described in the catalog
(SQLSTATE 42710). If a two part name is specified, the schema name
cannot begin with "SYS" (SQLSTATE 42939).
- NO CASCADE BEFORE
- Specifies that the associated triggered action is to be applied before any
changes caused by the actual update of the subject table are applied to the
database. It also specifies that the triggered action of the trigger
will not cause other triggers to be activated.
- AFTER
- Specifies that the associated triggered action is to be applied after the
changes caused by the actual update of the subject table are applied to the
database.
- INSERT
- Specifies that the triggered action associated with the trigger is to be
executed whenever an INSERT operation is applied to the designated base
table.
- DELETE
- Specifies that the triggered action associated with the trigger is to be
executed whenever a DELETE operation is applied to the designated base
table.
- UPDATE
- Specifies that the triggered action associated with the trigger is to be
executed whenever an UPDATE operation is applied to the designated base table
subject to the columns specified or implied.
If the optional column-name list is not specified, every column of
the table is implied. Therefore, omission of the column-name
list implies that the trigger will be activated by the update of any column of
the table.
- OF column-name,...
- Each column-name specified must be a column of the base table
(SQLSTATE 42703). If the trigger is a BEFORE trigger, the
column-name specified may not be a generated column other than the
identity column (SQLSTATE 42989). No column-name shall appear
more than once in the column-name list (SQLSTATE 42711). The
trigger will only be activated by the update of a column identified in the
column-name list.
- ON table-name
- Designates the subject table of the trigger definition. The name
must specify a base table or an alias that resolves to a base table (SQLSTATE
42809). The name must not specify a catalog table (SQLSTATE 42832), a
summary table (SQLSTATE 42997), a declared temporary table (SQLSTATE 42995),
or a nickname (SQLSTATE 42809).
- REFERENCING
- Specifies the correlation names for the transition variables
and the table names for the transition tables. Correlation
names identify a specific row in the set of rows affected by the triggering
SQL operation. Table names identify the complete set of affected
rows. Each row affected by the triggering SQL operation is available to
the triggered action by qualifying columns with correlation-names
specified as follows.
- OLD AS correlation-name
- Specifies a correlation name which identifies the row state prior to the
triggering SQL operation.
- NEW AS correlation-name
- Specifies a correlation name which identifies the row state as modified by
the triggering SQL operation and by any SET statement in a BEFORE trigger that
has already executed.
The complete set of rows affected by the triggering SQL operation is
available to the triggered action by using a temporary table name specified as
follows.
- OLD_TABLE AS identifier
- Specifies a temporary table name which identifies the set of affected rows
prior to the triggering SQL operation.
- NEW_TABLE AS identifier
- Specifies a temporary table name which identifies the affected rows as
modified by the triggering SQL operation and by any SET statement in a BEFORE
trigger that has already executed.
The following rules apply to the REFERENCING clause:
- None of the OLD and NEW correlation names and the OLD_TABLE and
NEW_TABLE names can be identical (SQLSTATE 42712).
- Only one OLD and one NEW correlation-name may be specified for a
trigger (SQLSTATE 42613).
- Only one OLD_TABLE and one NEW_TABLE identifier may be specified
for a trigger (SQLSTATE 42613).
- The OLD correlation-name and the OLD_TABLE identifier
can only be used if the trigger event is either a DELETE operation or an
UPDATE operation (SQLSTATE 42898). If the operation is a DELETE
operation, OLD correlation-name captures the value of the deleted
row. If it is an UPDATE operation, it captures the value of the row
before the UPDATE operation. The same applies to the OLD_TABLE
identifier and the set of affected rows.
- The NEW correlation-name and the NEW_TABLE identifier
can only be used if the trigger event is either an INSERT operation or an
UPDATE operation (SQLSTATE 42898). In both operations, the value of NEW
captures the new state of the row as provided by the original operation and as
modified by any BEFORE trigger that has executed to this point. The
same applies to the NEW_TABLE identifier and the set of affected
rows.
- OLD_TABLE and NEW_TABLE identifiers cannot be defined for a
BEFORE trigger (SQLSTATE 42898).
- OLD and NEW correlation-names cannot be defined for a FOR EACH
STATEMENT trigger (SQLSTATE 42899).
- Transition tables cannot be modified (SQLSTATE 42807).
- The total of the references to the transition table columns and transition
variables in the triggered-action cannot exceed the limit for the number of
columns in a table or the sum of their lengths cannot exceed the maximum
length of a row in a table (SQLSTATE 54040).
- The scope of each correlation-name and each identifier
is the entire trigger definition.
- FOR EACH ROW
- Specifies that the triggered action is to be applied once for each row of
the subject table that is affected by the triggering SQL operation.
- FOR EACH STATEMENT
- Specifies that the triggered action is to be applied only once for the
whole statement. This type of trigger granularity cannot be specified
for a BEFORE trigger (SQLSTATE 42613). If specified, an UPDATE or
DELETE trigger is activated even when no rows are affected by the triggering
UPDATE or DELETE statement.
- MODE DB2SQL
- This clause is used to specify the mode of triggers. This is the
only valid mode currently supported.
- triggered-action
- Specifies the action to be performed when a trigger is activated. A
triggered-action is composed of one or several
triggered-SQL-statements and by an optional condition for the
execution of the triggered-SQL-statements. If there is more
than one triggered-SQL-statement in the triggered-action for a given
trigger, they must be enclosed within the BEGIN ATOMIC and END keywords,
separated by a semi-colon,
83
and are executed in the order they are
specified.
- WHEN (search-condition)
- Specifies a condition that is true, false, or unknown. The
search-condition provides a capability to determine whether or not a
certain triggered action should be executed.
The associated action is performed only if the specified search condition
evaluates as true. If the WHEN clause is omitted, the associated
triggered-SQL-statements are always performed.
- triggered-SQL-statement
- If the trigger is a BEFORE trigger, then a triggered SQL statement must be
one of the following (SQLSTATE 42987):
- a fullselect 84
- a SET transition-variable SQL statement.
- a SIGNAL SQLSTATE statement
If the trigger is an AFTER trigger, then a triggered SQL statement must be
one of the following (SQLSTATE 42987):
- an INSERT SQL statement
- a searched UPDATE SQL statement
- a searched DELETE SQL statement
- a SIGNAL SQLSTATE statement
- a fullselect 84
The triggered-SQL-statement cannot reference an undefined
transition variable (SQLSTATE 42703) or a declared temporary table (SQLSTATE
42995).
The triggered-SQL-statement in a BEFORE trigger cannot reference a
summary table defined with REFRESH IMMEDIATE (SQLSTATE 42997).
The triggered-SQL-statement in a BEFORE trigger cannot reference a
generated column, other than the identity column, in the new transition
variable (SQLSTATE 42989).
Notes
- Adding a trigger to a table that already has rows in it will not cause any
triggered actions to be activated. Thus, if the trigger is designed to
enforce constraints on the data in the table, those constraints may not be
satisfied by the existing rows.
- If the events for two triggers occur simultaneously (for example, if they
have the same event, activation time, and subject tables), then the first
trigger created is the first to execute.
- If a column is added to the subject table after triggers have been
defined, the following rules apply:
- If the trigger is an UPDATE trigger that was specified without an explicit
column list, then an update to the new column will cause the activation of the
trigger.
- The column will not be visible in the triggered action of any previously
defined trigger.
- The OLD_TABLE and NEW_TABLE transition tables will not contain this
column. Thus, the result of performing a "SELECT *" on a transition
table will not contain the added column.
- If a column is added to any table referenced in a triggered action, the
new column will not be visible to the triggered action.
- The result of a fullselect specified as a triggered-SQL-statement
is not available inside or outside of the trigger.
- A before delete trigger defined on a table involved in a cycle of cascaded
referential constraints should not include references to the table on which it
is defined or any other table modified by cascading during the evaluation of
the cycle of referential integrity constraints. The results of such a
trigger are data dependent and therefore may not produce consistent
results.
In its simplest form, this means that a before delete trigger on a table
with a self-referencing referential constraint and a delete rule of CASCADE
should not include any references to the table in the
triggered-action.
- The creation of a trigger causes certain packages to be marked
invalid:
- If an update trigger without an explicit column list is created, then
packages with an update usage on the target table are invalidated.
- If an update trigger with a column list is created, then packages with
update usage on the target table are only invalidated if the package also has
an update usage on at least one column in the column-name list of the
CREATE TRIGGER statement.
- If an insert trigger is created, packages that have an insert usage on the
target table are invalidated.
- If a delete trigger is created, packages that have a delete usage on the
target table are invalidated.
- A package remains invalid until the application program is explicitly
bound or rebound, or it is executed and the database manager automatically
rebinds it.
- Inoperative triggers:
An inoperative
trigger is a trigger that is no longer available and is therefore never
activated. A trigger becomes inoperative if:
- A privilege that the creator of the trigger is required to have for the
trigger to execute is revoked.
- An object such as a table, view or alias, upon which the triggered action
is dependent, is dropped.
- A view, upon which the triggered action is dependent, becomes
inoperative.
- An alias that is the subject table of the trigger is dropped.
In practical terms, an inoperative trigger is one in which a trigger
definition has been dropped as a result of cascading rules for DROP or REVOKE
statements. For example, when an view is dropped, any trigger with a
triggered-SQL-statement defined using that view is made
inoperative.
When a trigger is made inoperative, all packages with statements performing
operations that were activating the trigger will be marked invalid.
When the package is rebound (explicitly or implicitly) the inoperative
trigger is completely ignored. Similarly, applications with
dynamic SQL statements performing operations that were activating the trigger
will also completely ignore any inoperative triggers.
The trigger name can still be specified in the DROP TRIGGER and COMMENT ON
TRIGGER statements.
An inoperative trigger may be recreated by issuing a CREATE TRIGGER
statement using the definition text of the inoperative trigger. This
trigger definition text is stored in the TEXT column of
SYSCAT.TRIGGERS. Note that there is no need to explicitly drop
the inoperative trigger in order to recreate it. Issuing a CREATE
TRIGGER statement with the same trigger-name as an inoperative
trigger will cause that inoperative trigger to be replaced with a warning
(SQLSTATE 01595).
Inoperative triggers are indicated by an X in the VALID column of the
SYSCAT.TRIGGERS catalog view.
- Errors executing triggers:
Errors that occur during the execution of triggered-SQL-statements are
returned using SQLSTATE 09000 unless the error is considered severe. If
the error is severe, the severe error SQLSTATE is returned. The
SQLERRMC field of the SQLCA for non-severe error will include the trigger
name, SQLCODE, SQLSTATE and as many tokens as will fit from the tokens of the
failure.
A triggered-SQL-statement could be a SIGNAL SQLSTATE statement or
contain a RAISE_ERROR function. In both these cases, the SQLSTATE
returned is the one specified in the SIGNAL SQLSTATE statement or the
RAISE_ERROR condition.
- Creating a trigger with a schema name that does not already exist will
result in the implicit creation of that schema provided the authorization ID
of the statement has IMPLICIT_SCHEMA authority. The schema owner is
SYSIBM. The CREATEIN privilege on the schema is granted to
PUBLIC.
- A value generated by the database manager for an identity column is
generated before the execution of any BEFORE triggers. Therefore, the
generated identity value is visible to BEFORE triggers.
- A value generated by the database manager for a generated by expression
column is generated after the execution of all BEFORE
triggers.Therefore, the value generated by the expression is not
visible to BEFORE triggers.
- Triggers and typed tables:
A trigger can be attached to a typed table at any level of a table
hierarchy. If an SQL statement activates multiple triggers, the
triggers will be executed in their creation order, even if they are attached
to different tables in the typed table hierarchy.
When a trigger is activated, its transition variables (OLD, NEW, OLD_TABLE
and NEW_TABLE) may contain rows of subtables. However, they will
contain only columns defined on the table to which they are attached.
Effects of INSERT, UPDATE, and DELETE statements:
- Row triggers: When an SQL statement is used to INSERT, UPDATE, or
DELETE a table row, it activates row-triggers attached to the most specific
table containing the row, and all supertables of that table. This rule
is always true, regardless of how the SQL statement accesses the table.
For example, when issuing an UPDATE EMP command, some of the updated rows may
be in the subtable MGR. For EMP rows, the row-triggers attached to EMP
and its supertables are activated. For MGR rows, the row-triggers
attached to MGR and its supertables are activated.
- Statement triggers: An INSERT, UPDATE, or DELETE statement activates
statement-triggers attached to tables (and their supertables) that could be
affected by the statement. This rule is always true, regardless of
whether any actual rows in these tables were affected. For example, on
an INSERT INTO EMP command, statement-triggers for EMP and its supertables are
activated. As another example, on either an UPDATE EMP or DELETE EMP
command, statement triggers for EMP and its supertables and subtables are
activated, even if no subtable rows were updated or deleted. Likewise,
a UPDATE ONLY (EMP) or DELETE ONLY (EMP) command will activate
statement-triggers for EMP and its supertables, but not statement-triggers for
subtables.
Effects of DROP TABLE statements: A DROP TABLE statement does not
activate any triggers that are attached to the table being dropped.
However, if the dropped table is a subtable, all the rows of the dropped table
are considered to be deleted from its supertables. Therefore, for a
table T:
- Row triggers: DROP TABLE T activates row-type delete-triggers that
are attached to all supertables of T, for each row of T.
- Statement triggers: DROP TABLE T activates statement-type
delete-triggers that are attached to all supertables of T, regardless of
whether T contains any rows.
Actions on Views: To predict what triggers are activated by an action
on a view, use the view definition to translate that action into an action on
base tables. For example:
- An SQL statement performs UPDATE V1, where V1 is a typed view with a
subview V2. Suppose V1 has underlying table T1, and V2 has underlying
table T2. The statement could potentially affect rows in T1, T2, and
their subtables, so statement triggers are activated for T1 and T2 and all
their subtables and supertables.
- An SQL statement performs UPDATE V1, where V1 is a typed view with a
subview V2. Suppose V1 is defined as SELECT ...
FROM ONLY(T1) and V2 is defined as SELECT ... FROM
ONLY(T2). Since the statement cannot affect rows in subtables of T1 and
T2, statement triggers are activated for T1 and T2 and their supertables, but
not their subtables.
- An SQL statement performs UPDATE ONLY(V1), where V1 is a typed view
defined as SELECT ... FROM T1. The statement can
potentially affect T1 and its subtables. Therefore, statement triggers
are activated for T1 and all its subtables and supertables.
- An SQL statement performs UPDATE ONLY(V1), where V1 is a typed view
defined as SELECT ... FROM ONLY(T1). In this case,
T1 is the only table that can be affected by the statement, even if V1 has
subviews and T1 has subtables. Therefore, statement triggers are
activated only for T1 and its supertables.
Examples
Example 1: Create two triggers that will result in
the automatic tracking of the number of employees a company manages.
The triggers will interact with the following tables:
- EMPLOYEE table with these columns: ID, NAME, ADDRESS, and
POSITION.
- COMPANY_STATS table with these columns: NBEMP, NBPRODUCT, and
REVENUE.
The first trigger increments the number of employees each time a new person
is hired; that is, each time a new row is inserted into the EMPLOYEE
table:
CREATE TRIGGER NEW_HIRED
AFTER INSERT ON EMPLOYEE
FOR EACH ROW MODE DB2SQL
UPDATE COMPANY_STATS SET NBEMP = NBEMP + 1
The second trigger decrements the number of employees each time an employee
leaves the company; that is, each time a row is deleted from the table
EMPLOYEE:
CREATE TRIGGER FORMER_EMP
AFTER DELETE ON EMPLOYEE
FOR EACH ROW MODE DB2SQL
UPDATE COMPANY_STATS SET NBEMP = NBEMP - 1
Example 2: Create a trigger that ensures that
whenever a parts record is updated, the following check and (if necessary)
action is taken:
- If the on-hand quantity is less than 10% of the maximum stocked quantity,
then issue a shipping request ordering the number of items for the affected
part to be equal to the maximum stocked quantity minus the on-hand
quantity.
The trigger will interact with the PARTS table with these columns:
PARTNO, DESCRIPTION, ON_HAND, MAX_STOCKED, and PRICE.
ISSUE_SHIP_REQUEST is a user-defined function that sends an order form for
additional parts to the appropriate company.
CREATE TRIGGER REORDER
AFTER UPDATE OF ON_HAND, MAX_STOCKED ON PARTS
REFERENCING NEW AS N
FOR EACH ROW MODE DB2SQL
WHEN (N.ON_HAND < 0.10 * N.MAX_STOCKED)
BEGIN ATOMIC
VALUES(ISSUE_SHIP_REQUEST(N.MAX_STOCKED - N.ON_HAND, N.PARTNO));
END
Example 3: Create a trigger that will cause an error
when an update occurs that would result in a salary increase greater than ten
percent of the current salary.
CREATE TRIGGER RAISE_LIMIT
AFTER UPDATE OF SALARY ON EMPLOYEE
REFERENCING NEW AS N OLD AS O
FOR EACH ROW MODE DB2SQL
WHEN (N.SALARY > 1.1 * O.SALARY)
SIGNAL SQLSTATE '75000' ('Salary increase>10%')
Example 4: Consider an application which records and
tracks changes to stock prices. The database contains two tables,
CURRENTQUOTE and QUOTEHISTORY.
Tables: CURRENTQUOTE (SYMBOL, QUOTE, STATUS)
QUOTEHISTORY (SYMBOL, QUOTE, QUOTE_TIMESTAMP)
When the QUOTE column of CURRENTQUOTE is updated, the new quote should be
copied, with a timestamp, to the QUOTEHISTORY table. Also, the STATUS
column of CURRENTQUOTE should be updated to reflect whether the stock
is:
- rising in value;
- at a new high for the year;
- dropping in value;
- at a new low for the year;
- steady in value.
CREATE TRIGGER statements that accomplish this are as follows.
- Trigger Definition to set the status:
CREATE TRIGGER STOCK_STATUS
NO CASCADE BEFORE UPDATE OF QUOTE ON CURRENTQUOTE
REFERENCING NEW AS NEWQUOTE OLD AS OLDQUOTE
FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
SET NEWQUOTE.STATUS =
CASE
WHEN NEWQUOTE.QUOTE >
(SELECT MAX(QUOTE) FROM QUOTEHISTORY
WHERE SYMBOL = NEWQUOTE.SYMBOL
AND YEAR(QUOTE_TIMESTAMP) = YEAR(CURRENT DATE) )
THEN 'High'
WHEN NEWQUOTE.QUOTE <
(SELECT MIN(QUOTE) FROM QUOTEHISTORY
WHERE SYMBOL = NEWQUOTE.SYMBOL
AND YEAR(QUOTE_TIMESTAMP) = YEAR(CURRENT DATE) )
THEN 'Low'
WHEN NEWQUOTE.QUOTE > OLDQUOTE.QUOTE
THEN 'Rising'
WHEN NEWQUOTE.QUOTE < OLDQUOTE.QUOTE
THEN 'Dropping'
WHEN NEWQUOTE.QUOTE = OLDQUOTE.QUOTE
THEN 'Steady'
END;
END
- Trigger Definition to record change in QUOTEHISTORY table:
CREATE TRIGGER RECORD_HISTORY
AFTER UPDATE OF QUOTE ON CURRENTQUOTE
REFERENCING NEW AS NEWQUOTE
FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
INSERT INTO QUOTEHISTORY
VALUES (NEWQUOTE.SYMBOL, NEWQUOTE.QUOTE, CURRENT TIMESTAMP);
END
Footnotes:
- 83
-
When using this form in the Command Line Processor, the statement terminating
character cannot be the semi-colon. See the Command
Reference for information on specifying an alternative terminating
character.
- 84
-
A common-table-expression may precede a fullselect.
[ Top of Page | Previous Page | Next Page ]