UPDATE Same Row After UPDATE in Trigger
Asked Answered
P

2

11

I want the epc column to always be earnings/clicks. I am using an AFTER UPDATE trigger to accomplish this. So if I were to add 100 clicks to this table, I would want the EPC to update automatically.

I am trying this:

CREATE TRIGGER `records_integrity` AFTER UPDATE ON `records` FOR EACH ROW SET 
NEW.epc=IFNULL(earnings/clicks,0);

And getting this error:

MySQL said: #1362 - Updating of NEW row is not allowed in after trigger

I tried using OLD as well but also got an error. I could do BEFORE but then if I added 100 clicks it would use the previous # clicks for the trigger (right?)

What should I do to accomplish this?

EDIT - An example of a query that would be run on this:

UPDATE records SET clicks=clicks+100
//EPC should update automatically
Peloquin answered 24/7, 2013 at 0:53 Comment(0)
P
15

You can't update rows in the table in an after update trigger.

Perhaps you want something like this:

CREATE TRIGGER `records_integrity` BEFORE UPDATE
ON `records`
FOR EACH ROW
    SET NEW.epc=IFNULL(new.earnings/new.clicks, 0);

EDIT:

Inside a trigger, you have have access to OLD and NEW. OLD are the old values in the record and NEW are the new values. In a before trigger, the NEW values are what get written to the table, so you can modify them. In an after trigger, the NEW values have already been written, so they cannot be modified. I think the MySQL documentation explains this pretty well.

Purview answered 24/7, 2013 at 0:55 Comment(6)
@hellohellosharp . . . Somehow it wasn't when I looked at the code. ;)Purview
Thanks for updating - your answer appears to be working. I am confused though...wouldn't a BEFORE update use the wrong values for clicks and earnings?Peloquin
@hellohellosharp . . . That is the difference between old and new. The set is using the new values.Purview
Makes sense...and I will accept your answer ASAP. I guess I don't understand how a BEFORE statement would know the NEW values.Peloquin
How i can do a WHERE id=id after SET statemnent?Ainsley
@KingsleyChew . . .You should ask a new question as a question, not a comment.Purview
F
0

Perhaps you could write two separate statements in that transaction

 update record set clicks=...

 update record set epc=...

or you could put them inside a function, say updateClick() and just call that function. By doing it this way you can easily alter your logic should the need arise.

Putting the logic inside a trigger might create a situation where debugging and tracing are made unnecessarily complex.

Fuge answered 24/7, 2013 at 5:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.