Reputation:
I have to create the trigger(s) which will keep the audit of my table. The trigger is supposed to execute on both insert and update.
currently i am having two triggers
One for Insert:
CREATE TRIGGER SCH.TRG_TBL1_AFT_I
AFTER INSERT ON SCH.TBL1
REFERENCING
NEW AS n
FOR EACH ROW
MODE DB2SQL
INSERT INTO SCH.TBL1_AUDIT
VALUES( .. ,, .. );
Another for update
CREATE TRIGGER SCH.TRG_TBL1_AFT_U
AFTER UPDATE ON SCH.TBL1
REFERENCING
NEW AS n
FOR EACH ROW
MODE DB2SQL
INSERT INTO SCH.TBL1_AUDIT
VALUES( .. ,, .. );
But the point is, if it possible to create a single trigger, in DB2, for doing the task? [ provided both, trigger are doing the same thing .]
Upvotes: 5
Views: 7826
Reputation: 116
Try this, the feature has been available since version 9.7.x.
CREATE or replace TRIGGER PASSENGER_TR01_BEFORE_IUD
BEFORE
DELETE
OR UPDATE OF FIRST_NAME
OR INSERT ON PASSENGER
REFERENCING
OLD AS oldRow
NEW AS newRow
FOR EACH ROW
WHEN (1=1)
Begin
Declare ACTION Char(1) Default '';
-- Use Case/When to inquire trigger-event
Case
When INSERTING Then
Set ACTION='I';
When UPDATING Then
Set ACTION='U';
When DELETING Then
Set ACTION='D';
Else
Set ACTION='N';
End Case;
-- Use If/Then/Else to inquire trigger-event
If INSERTING Then
Set ACTION='I';
ElseIf UPDATING Then
Set ACTION='U';
ElseIf DELETING Then
Set ACTION='D';
Else
Set ACTION='N';
End If;
End
Upvotes: 4
Reputation: 3
CREATE OR REPLACE TRIGGER SET_SALARY
NO CASCADE
BEFORE UPDATE OR INSERT ON employee
REFERENCING NEW AS n OLD AS o
FOR EACH ROW
WHEN( o.edlevel IS NULL OR n.edlevel > o.edlevel )
BEGIN
-- Give 10% raise to existing employees with new education level.
IF UPDATING THEN SET n.salary = n.salary * 1.1;
-- Give starting salary based on education level.
ELSEIF INSERTING THEN
SET n.salary = CASE n.edlevel WHEN 18 THEN 50000
WHEN 16 THEN 40000
ELSE 25000
END;
END IF;
END
Upvotes: 0
Reputation: 25069
Yes it is possible. See the documentation of create trigger. Here is a paste:
trigger-event
.-OR--------------------------------------.
V (4) |
|----+-INSERT--------------------------+-----+------------------|
+-DELETE--------------------------+
'-UPDATE--+---------------------+-'
| .-,-----------. |
| V | |
'-OF----column-name-+-'
That would enable you to say:
create trigger blah before insert on blah or update of blah
.
Upvotes: 2
Reputation: 5332
Sorry, DB2 doesn't offer a way to combine update and insert triggers together.
Upvotes: -1