3

我有 1 个这样的表:

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

我想编写一个触发器,它将 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.

4

2 回答 2

7

当 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 ;
于 2013-03-16T05:40:57.077 回答
2

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

希望这可以帮到你。


    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

于 2013-03-16T05:46:42.353 回答