Question

I'm trying to create a trigger which updates a entire table where Name='test_user'. Here is what I got so far:

CREATE TRIGGER users.insert_log 
AFTER INSERT ON users.logBook
FOR EACH ROW
UPDATE users.logBook
SET UserName = 'SQL_TEST'
WHERE
UserName = 'test_user';

It creates my trigger without any problems. But when inserting i get this error:

ERROR 1442 (HY000): Can't update table 'logBook' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

How do I update my rows where UserName = test_user?

Was it helpful?

Solution

This is a bizarre use of triggers, but if you really want this to happen, maybe calling a function from the trigger would work.

Alternatively, why not try an INSTEAD OF trigger and replace the UserName with SQL_TEST only if it equals test_user? I'm guessing that's what you're trying to achieve?

For example:

CREATE TRIGGER users.insert_log 
BEFORE INSERT ON users.logBook
FOR EACH ROW
BEGIN
IF NEW.UserName = 'test_user' THEN
SET NEW.UserName = 'SQL_TEST';
END IF;
END;

OTHER TIPS

What is your intention with that? Imho it looks like you try to fix a bug that happend someplace else. Anyway this does not seam to work for mysql, as mysql can not handle updates on the same table in a trigger.

see: http://forums.mysql.com/read.php?99,122354,249709#msg-249709

It is better to update the table first to replace the existing values. Then create a trigger like this to filter the new values:

CREATE TRIGGER users.insert_log BEFORE INSERT ON users.logBook
  FOR EACH ROW
BEGIN
    IF NEW.UserName = 'test_user' THEN
        SET NEW.UserName = 'SQL_TEST';
    END IF;
END;

I am not sure if you want to reset the new username data.
But if yes, change your trigger as BEFORE TRIGGER.

Try this:

CREATE TRIGGER users.insert_log 
  BEFORE INSERT ON users.logBook
  FOR EACH ROW
    SET NEW.UserName = case when NEW.username = 'test_user' then 'SQL_TEST' 
                            else NEW.username
                       end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top