Conditional SQL Trigger Example

Conditional SQL Trigger Example
Conditional SQL Trigger Example, SQL trigger, trigger, db2, db2 for i sql, sql , sql programming, ibmi, as400, iseries
Conditional SQL Trigger Example

Introduction

This article will explain a conditional SQL trigger example.

Below are the table structures that will be used in the example

Table1 

A          R RTGPF1             
A            ROLLNO         9P 0
A            NAME          10A  
A            COLLEGE       50A  
A          K ROLLNO            

Table2

A          R RTGPF2              
A            STUCNT         9P 0 

Trigger Execution

The trigger will be added to TABLE1 and it will get triggered when any record is updated in the table. 

Trigger Condition

When the value of the COLLEGE  field from TABLE1 gets changed.

Trigger Action

Only when the trigger condition is true, only the STUCNT field from TABLE2 gets increment by 1.

Example: Conditional Trigger

In this example, the UPDATE_STUDENT trigger gets created and if already present then that will be replaced by this trigger.

CREATE OR REPLACE TRIGGER UPDATE_STUDENT   
AFTER UPDATE ON TRGPF1                     
REFERENCING NEW ROW AS NEW OLD ROW AS OLD  
FOR EACH ROW MODE DB2ROW                   
WHEN(NEW.COLLEGE <> OLD.COLLEGE)           
BEGIN                                      
UPDATE TRGPF2 SET STUCNT = STUCNT + 1;     
END;                                        

The below statement is fetching the current row and the old row values 

REFERENCING NEW ROW AS NEW OLD ROW AS OLD 
And, below is the condition that is comparing the old COLLEGE field value and the new COLLEGE field value.

WHEN(NEW.COLLEGE <> OLD.COLLEGE) 

Trigger object is a CLE program object which can be debugged.

Related Post

You may like these posts

  • SQL MIN scalar function in DB2 for i SQL MIN The MIN function returns the minimum value in a set of values. We should pass at least 2 arguments. Syntax MIN(arg1, arg2, arg3, …
  • SQL MINUTE scalar function in DB2 for i SQL MINUTE The MINUTE function returns the minute part of a value. Syntax MICROSECOND(expression) the expression must be either time …
  • SQL MICROSECOND scalar function in DB2 for i SQL MICROSECOND The MICROSECOND function returns the microsecond part of a timestamp value. Syntax MICROSECOND(expression) the exp…
  • SQL MAX scalar function in DB2 for i SQL MAX The MAX function returns the maximum value in a set of values. We should pass at least 2 arguments. Syntax MAX(arg1, arg2, arg3, …
  • SQL MOD scalar function in DB2 for i SQL MOD The MOD function returns the remainder by dividing the first numeric expression by the second numeric expression. Syntax MOD(numeri…
  • SQL LTRIM scalar function in DB2 for i SQL LTRIM The LTRIM function removes all of the characters that are passed in the trim-expression from the starting of the passed string ex…

Post a Comment