Database Fundamentals Lab07
Database Fundamentals Lab07
Tutorial 7
SQL - Triggers
Objective: To create simple triggers in DB2 and examine the effects when the
triggers are activated. Since different DBMSs provide different ways of creating
triggers, this practical is intended to give just a ‘flavour’ of triggers. You will need
to find out from the DBMS that you use how triggers can be created. For DB2,
more details can be found from the Information Centre.
1. Start DB2 and create the following table and insert five records into the table as
shown in the table below:
2. Enter the following commands to create a trigger. When will this trigger be activated?
What will happen to the database?
3. Type ‘SELECT * FROM PRODUCT’ to examine the contents of the table. Take
note of the p_reorder column.
6. In DB2, you need to create different triggers for different events. Create the following
trigger for the same table.
7. Execute the following SQL command to change the quantity on hand of item ‘A0001’.
Update product
Set p_onhand = 4
Where p_code = 'A0001';
8. Type ‘SELECT * FROM PRODUCT’ to examine the contents of the table. Is the
p_reorder column updated for the item A0001?
11. Remove trigger reorder2 using the command ‘DROP TRIGGER REORDER2’.
Rewrite the trigger as the following.
12. Execute the following SQL command to change the quantity on hand of item ‘A0007’
Update product2
Set p_onhand =8
Where p_code= 'A0007';
13. Type ‘SELECT * FROM PRODUCT2’, what is the value of p_reorder column for
item ‘A0007’?
13. This time execute another SQL command to change the p_min of item ‘A0007’
Update product2
Set p_min=7
Where p_code= 'A0007';
14. Type ‘SELECT * FROM PRODUCT2’ again, what is the value of p_reorder column
for item ‘A0007’ now?
Extra Exercises:
1. Remove the trigger reorder1 using the command ‘DROP TRIGGER REORDER1’.
Rewrite the trigger so that p_reorder is also updated when p_onhand is less than
p_min_order. Create and test the trigger.
2. Create a new trigger that will set the discount of an item automatically when a new
item record is inserted. The discount is 0.05 for item below 15.00 and 0.10 for 15.00
and above.