问题
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?
回答1:
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);
来源:https://stackoverflow.com/questions/39838235/mysql-error-1442-when-triggering-an-action-to-update-two-columns-after-inserting