how to create trigger to do concatenation of field

2019-04-12 01:24发布

问题:

I have 1 table like this:

user
----------------------------------------
id | first_name | last_name | full_name
----------------------------------------

I want to write a trigger which will concat the first_name and last_name to full_name.

I have tried below trigger :

delimiter |
create trigger fullname after insert on user
for each row
begin
update user set full_name=(select concat(first_name,last_name) from user where id=new.id)where id=new.id;
end;
|

It's shows this error while inserting data to user table:

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

回答1:

You cannot change a table while the INSERT trigger is firing. You can, however, create a trigger before inserting the record.

DELIMITER |
CREATE TRIGGER `fullname` BEFORE INSERT ON `user`
FOR EACH ROW 
BEGIN
  SET NEW.full_name = CONCAT(NEW.first_name, ' ', NEW.last_name);
END |
DELIMITER ;


回答2:

For your case, I would like to suggest you to use computed column instead of trigger, because trigger you need to create for insert/update;

Hope this can help you.


    create table [users] 
    ( id int identity(1,1),
      First_Name varchar(100),
      Last_Name varchar(100),
      Full_Name as concat(First_Name,' ', Last_Name) persisted
   )
      Insert into [users]
      select 'Bob', 'Ryan'

     select * from [users]

    update users 
    set First_Name = 'Michael'
    where id=1

    select * from users