2013-03-16 70 views
2

的級聯我有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.

+0

檢查:http://stackoverflow.com/questions/12877732/mysql-trigger-for-updating-same-table-after-insert – mavili 2013-03-16 05:41:47

回答

6

你不能改變一個表,而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 ; 
+0

哎呀我的錯誤這個邏輯在插入記錄之前創建觸發器並沒有打擊我的腦海....它的工作:) thnk你先生... !!! – 2013-03-16 05:52:02

1

對於你的情況,我想建議你使用計算列而不是觸發器,因爲觸發器需要爲insert/update創建;

希望這可以幫助你。


    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