4

I have two tables:

sanction with these attributes: DriverID, Calification, Points
people with these attributes: pID, city , TotalPoints

And i have this trigger:

DROP TRIGGER IF EXISTS updatePoints_tgr;

delimiter $$
CREATE  TRIGGER
updatePoints_tgr AFTER UPDATE
ON sanctions FOR EACH ROW
 BEGIN
     if NEW.points > OLD.points 
     THEN
         UPDATE people
         SET TotalPoints = TotalPoints + (NEW.points - OLD.points)
         WHERE people.pID = NEW.DriverID;
     elseif NEW.points < OLD.points 
     THEN
         UPDATE people
         SET TotalPoints = TotalPoints - (NEW.points - OLD.points)
         WHERE people.pID = NEW.DriverID;
     END IF;
 END$$
 delimiter ;

And when I try to execute this update

UPDATE sanctions 
JOIN people ON sanctions.DriverID=people.pID
SET points=points+6
WHERE city='Barcelona'  AND Calification='LightPenalty'

I get this error:

Can't update table 'people' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

How can i fix it? Thanks.

I use Windows 10 and MySQL server 5.7.17

Martin
  • 22,212
  • 11
  • 70
  • 132
J.Coe
  • 65
  • 5

1 Answers1

0

You cannot update a table (sanctions and people) where the trigger is invoked:

Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

Doing so will generate Error 1442:

Error Code: 1442
Can't update table 'MyTable' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

Your case: The confusion can be due to the JOIN on sanctions and people for the UPDATE - making both the table in use, as stated above 'used' means 'reading or writing'.


To test - Try the UPDATE query without the JOIN (with people) - if it works, surely it is the case.

Nabeel Ahmed
  • 18,328
  • 4
  • 58
  • 63