IBM Database Add-Ins for Visual Studio  

CREATE TRIGGER Sample SQL  (DB2)

The following examples show sample SQL code for creating different types of DB2® triggers.

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:

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
     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
     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:

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
     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
     WHEN (N.SALARY > 1.1 * O.SALARY)
            SIGNAL SQLSTATE '75000' SET MESSAGE_TEXT='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:

   1. rising in value
   2. at a new high for the year
   3. dropping in value
   4. at a new low for the year
   5. steady in value
    

CREATE TRIGGER statements that accomplish this are as follows.

See Also

IBM Database Triggers | Creating Triggers | Triggers, Designer


.NET Development Forum   developerWorks: Visual Studio .NET   DB2 FAQs

© Copyright IBM Corporation 2002, 2012. All Rights Reserved.