I want to set STATUS
column value to null before an update happen in TABLE_A
regardless whether the update changes the STATUS
column value or not. Suppose that the update statement looks like this
UPDATE TABLE_A SET STATUS=0, STATUS_A=1;
,
i want to change the STATUS
column value to null first before it is set to 0. Or if the update statement looks like this UPDATE TABLE_A SET STATUS_A=1;
, i want to change the STATUS
column value to null first. I created a trigger before update code like below
delimiter $$
CREATE TRIGGER DECISION_CHANGES BEFORE UPDATE ON TABLE_A
FOR EACH ROW
BEGIN
IF NEW.STATUS_A<>OLD.STATUS_A THEN
SET `STATUS` = NULL;
ELSEIF NEW.STATUS_T1<>OLD.STATUS_T1 AND NEW.STATUS_TL1<>OLD.STATUS_TL1 THEN
SET `STATUS` = NULL;
ELSEIF NEW.STATUS_T2<>OLD.STATUS_T2 AND NEW.STATUS_TL2<>OLD.STATUS_TL2 THEN
SET `STATUS` = NULL;
END IF;
END$$
delimiter ;
But those code give me error probably because i can only set new.STATUS
not STATUS
. But if i did that, it will be like overwriting the actual update values won't it?(In the end it would write null, not 0)
How do i do that with trigger?if i can't do that with trigger, is there any workaround? Thank you.
UPDATE 1. I dont really understand how exactly the data flow works on trigger with before update clause but i tried to code it like below. Will it does things as i expect it will?
delimiter $$
CREATE TRIGGER DECISION_CHANGES BEFORE UPDATE ON TABLE_A
FOR EACH ROW
BEGIN
DECLARE tempSTATUS INT;
DECLARE FLAG INT;
IF OLD.`STATUS`<>NEW.`STATUS` THEN
SET tempSTATUS=NEW.`STATUS`;
SET FLAG=1;
ELSEIF NEW.STATUS_T1<>OLD.STATUS_T1 AND NEW.STATUS_TL1<>OLD.STATUS_TL1 THEN
SET tempSTATUS=NEW.`STATUS`;
SET FLAG=1;
ELSEIF NEW.STATUS_T2<>OLD.STATUS_T2 AND NEW.STATUS_TL2<>OLD.STATUS_TL2 THEN
SET tempSTATUS=NEW.`STATUS`;
SET FLAG=1;
END IF;
IF NEW.STATUS_A<>OLD.STATUS_A THEN
SET `STATUS` = NULL;
ELSEIF NEW.STATUS_T1<>OLD.STATUS_T1 AND NEW.STATUS_TL1<>OLD.STATUS_TL1 THEN
SET `STATUS` = NULL;
ELSEIF NEW.STATUS_T2<>OLD.STATUS_T2 AND NEW.STATUS_TL2<>OLD.STATUS_TL2 THEN
SET `STATUS` = NULL;
END IF;
IF FLAG=1 THEN
SET NEW.`STATUS`=tempSTATUS;
END IF;
END$$
delimiter ;