After inserting data, for example, a date into a event_date
column, I want a trigger to update two columns of that same table and row the corresponding values of 'event_quarter' and 'event_year'.
I have this test table
with four columns:
id
, event_date
, event_quarter
, event_year
I have been struggling with this code to make it work:
DELIMITER $$
CREATE TRIGGER `fill_event_quarter_and_year`
AFTER INSERT
ON `test_table`
FOR EACH ROW
BEGIN
DECLARE event_date_ DATE;
SELECT event_date
INTO event_date_
FROM `test_table`
WHERE NEW.id = id;
UPDATE `test_table`
SET event_quarter = QUARTER(event_date_), event_year = YEAR(event_date_)
WHERE NEW.id = id;
END
$$
However, I get the following error:
1442 - Can't update table 'test_table' in stored function / trigger because it is already used by statement which invoked this stored
function / trigger
How do I fix it?
Then it looks like I have to make two triggers, one for this INSERT
ing action and another one for UPDATE
ing action. Right? How would that be when updating a specific row or record?
Or is it possible a trigger for both updating and inserting actions?
In a trigger, you cannot use the table you are changing for another query, this especially means that you cannot change or read other rows of that table. But you can actually change the row you are currently updating/inserting.
That row is refered to as
new
, and you can read and write to it, but you have to use the syntaxset new.columnname = ...
, withoutupdate
. This has to be done in abefore
-trigger.You cannot combine triggers for
update
andinsert
, so you have to create two, but you can use the same code for both: