New to MySql triggers, just learning.
CREATE TRIGGER MyTrigger
AFTER UPDATE ON MyTable
FOR EACH ROW
BEGIN
IF (new.field1 < 0 or new.field1 > 5) THEN
UPDATE new SET new.field1 = old.field1;
END IF;
END;
The goal is to keep the value of field1 the same, if the update puts it outside the range.
However, instead it sets it to 0. What am I doing wrong? How should this code look?
Here is an example that should hopefully get you started:
Why would it work better? Well first of all your example trigger is recursive, you can’t update the same table in a trigger that was triggered by an update.
Second, the
newin yourUPDATEstatement is not a table name, you need to specify one explicitly.It doesn’t appear to be a legit trigger at all, doesn’t your server complain when you try to create it? Can you perhaps show actually
SHOW CREATE TRIGGER `your_trigger`;to make sure that it’s really created and looks like you pasted it above?Even if your example would would work, you’re trying to do an unconstrained update on all rows of your table, not on the ones you’re trying to update, you should have a
WHEREclause; again, given that issue one and two are taken care of.