Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPDATE Same Row After UPDATE in Trigger

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
like image 345
kmoney12 Avatar asked Jul 24 '13 00:07

kmoney12


People also ask

Can we use update command in trigger?

AFTER UPDATE Trigger is a kind of trigger in SQL that will be automatically fired once the specified update statement is executed. It can be used for creating audit and log files which keep details of last update operations on a particular table.

How does after update trigger work?

An AFTER UPDATE Trigger means that Oracle will fire this trigger after the UPDATE operation is executed.

Does an on update trigger have access to old and new variables?

UPDATE. An UPDATE trigger can refer to both OLD and NEW transition variables. INSERT. An INSERT trigger can only refer to a NEW transition variable because before the activation of the INSERT operation, the affected row does not exist in the database.

What happens if after update trigger fails?

Failure of a trigger causes the statement to fail, so trigger failure also causes rollback. For nontransactional tables, such rollback cannot be done, so although the statement fails, any changes performed prior to the point of the error remain in effect.


1 Answers

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.

like image 107
Gordon Linoff Avatar answered Sep 23 '22 02:09

Gordon Linoff