Mysql error 1442 when triggering an action to upda

2019-09-03 15:40发布

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 INSERTing action and another one for UPDATEing 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?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-03 16:15

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 syntax set new.columnname = ..., without update. This has to be done in a before-trigger.

You cannot combine triggers for update and insert, so you have to create two, but you can use the same code for both:

CREATE TRIGGER `trbins_fill_event_quarter_and_year`
BEFORE INSERT ON `test_table`
FOR EACH ROW
  set new.event_quarter = QUARTER(new.event_date), 
      new.event_year = YEAR(new.event_date);

CREATE TRIGGER `trbupd_fill_event_quarter_and_year`
BEFORE UPDATE ON `test_table`
FOR EACH ROW
  set new.event_quarter = QUARTER(new.event_date), 
      new.event_year = YEAR(new.event_date);
查看更多
登录 后发表回答