patternsqlModerate
Trigger to UPDATE after UPDATE?
Viewed 0 times
aftertriggerupdate
Problem
I want to make a trigger to record the time of any update as:
The problem is that when this trigger tries to update the
How can I store the update time in the corresponding column?
I wish to use a trigger because there are many columns in the table. If I try to set the update time manually, I would need to modify many queries.
CREATE TRIGGER col_update
AFTER UPDATE ON col
FOR EACH ROW BEGIN
UPDATE col SET updated=NOW() WHERE id=NEW.id; // or OLD.id
ENDThe problem is that when this trigger tries to update the
updated column, it is also another update event, which runs the trigger. This will create an infinite loop, which does not work.How can I store the update time in the corresponding column?
I wish to use a trigger because there are many columns in the table. If I try to set the update time manually, I would need to modify many queries.
Solution
Use a
Your trigger body will simply look like
I usually use
BEFORE trigger instead, and set the updated column assigning a value to NEW.updated (this would be a simple assignment, not an UPDATE). This way you won't trigger additional UPDATEs.Your trigger body will simply look like
SET NEW.updated = NOW()I usually use
AFTER triggers only for modifying other tables, BEFORE for modifying the new (or updated) row, or suppress DELETE.Code Snippets
SET NEW.updated = NOW()Context
StackExchange Database Administrators Q#20328, answer score: 19
Revisions (0)
No revisions yet.