0

I've got a table like this

 id     firstname   lastname    fullname
 1      alex        car         alex car
 2      tony        table       tony table

If the firstname or lastname gets changed I want that the database automatically changes the fullname too.

I tried it with this trigger

CREATE TRIGGER mytrigger
AFTER UPDATE
   ON mytable FOR EACH ROW

BEGIN

    UPDATE `mydb`.`mytable` SET `fullname` = CONCAT(NEW.firstname, " ",NEW.lastname)    

END;

But I get this error:

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

Thanks you.

1 Answer 1

1

Use a before update trigger:

CREATE TRIGGER mytrigger BEFORE UPDATE
   ON mytable FOR EACH ROW
BEGIN
    set new.fullname = CONCAT(NEW.firstname, ' ' , NEW.lastname) ;
END;

As a note: your use of update would give you surprising results. The update has not where clause so it would set the fullname column in all rows in the table.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried it with a BEFORE trigger but it did not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.