I am trying to create a Trigger that will run through some IF ELSEIF statements and check the new value is NULL however it only goes to the first IF statement.
This Trigger is AFTER UPDATE. My question is if I am only SET one column value what are the others SET to, are they NULL or what. How can I test this column if it is not SET on this UPDATE command.
Example Update:
UPDATE `stations_us`.`current_prices` SET `midPrice` = '3.59' WHERE `current_prices`.`_id` =1;
There are other columns that do not update at this time but can be updated based on the PHP Script.
Trigger:
BEGIN
-- Definition start
IF(NEW.regPrice IS NOT NULL) THEN
INSERT INTO prices (stationID, price, type,
prevPrice, prevDate, dateCreated, apiKey, uid)
VALUES(NEW.stationID, NEW.regPrice, 'reg', OLD.regPrice,
OLD.regDate, NEW.regDate, NEW.lastApiUsed, NEW.lastUpdatedBy);
ELSEIF(NEW.midPrice IS NOT NULL) THEN
INSERT INTO prices (stationID, price, type,
prevPrice, prevDate, dateCreated, apiKey, uid)
VALUES(NEW.stationID, NEW.midPrice, 'mid', OLD.midPrice,
OLD.midDate, NEW.midDate, NEW.lastApiUsed, NEW.lastUpdatedBy);
ELSEIF(NEW.prePrice IS NOT NULL) THEN
INSERT INTO prices (stationID, price, type,
prevPrice, prevDate, dateCreated, apiKey, uid)
VALUES(NEW.stationID, NEW.prePrice, 'pre', OLD.prePrice,
OLD.preDate, NEW.preDate, NEW.lastApiUsed, NEW.lastUpdatedBy);
END IF;
-- Definition end
END
You can’t tell inside the trigger which columns were referenced in the SET clause.
You can only check whether the value of
colwas changed by the statement, by comparing the values ofNEW.colandOLD.col.Testing
(NEW.col IS NOT NULL)is not sufficient to tell whether the value has been changed. Consider the case when old value is e.g. 4.95 and the new value is NULL, it looks as if you probably want to detect that change.Note that an UPDATE statement may set values for more than one column:
Also note that a column may be set to NULL, and a column can be set to its existing value
In this case, inside your trigger,
NEW.col2would evaluate to NULL, and(NEW.col3 <=> OLD.col3)will evaluate to 1 (TRUE), because the OLD and NEW values are equal.(What your AFTER UPDATE trigger is really seeing is the value that got stored, which is not necessarily the value from your UPDATE statement if a BEFORE INSERT trigger has mucked with the value, and supplied a different value for that column.)
If your intent is to log changes in values, you probably do NOT want the ELSIF, but instead want to run through all the columns to check whether it’s value has been changed or not.