如何创建触发器做场串联(how to create trigger to do concatenat

2019-08-17 15:55发布

我有1台是这样的:

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

我想写一个触发器,它会在Concat的FIRST_NAME和last_name给FULL_NAME。

我曾尝试以下触发器:

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;
|

这显示了这个错误,同时插入数据的用户表:

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

Answer 1:

而INSERT触发器被解雇你不能改变一个表。 你可以,但是,插入记录之前创建触发器。

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 ;


Answer 2:

对于你的情况,我想建议你使用计算列的INSTEAD OF触发器,因为触发您需要创建插入/更新;

希望这可以帮到你。

 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 



文章来源: how to create trigger to do concatenation of fields