2013-07-12 334 views
1

我試圖計算百分比列在我的表project更新後發生在下列任何一欄fundgoal的。MYSQL觸發器來計算百分比

這是我做了查詢:

CREATE TRIGGER percentcalc AFTER UPDATE ON project 
    FOR EACH ROW 
    SET percent = (fund/goal) *100 

但我似乎得到一個錯誤:

#1193 - Unknown system variable 'percent'

回答

1
delimiter // 
CREATE TRIGGER percentcalc AFTER UPDATE ON project 
FOR EACH ROW BEGIN 
    SET NEW.percent = (NEW.fund/NEW.goal) * 100; 
END 
// 
delimiter ; 
1

主要有兩大問題:

  1. 你必須使用NEW關鍵字來訪問行的列的值正在更新
  2. 您無法在AFTER觸發器中更改NEW變量的值。如果你嘗試這樣做,你會得到'更新新行不允許在後觸發'錯誤。因此,你必須只使用BEFORE事件爲觸發器指定

Trigger Syntax and Examples
...Within the trigger body, the OLD and NEW keywords enable you to access columns in the rows affected by a trigger. (OLD and NEW are not case sensitive.)...

...In a BEFORE trigger, you can also change its value with SET NEW.col_name = value if you have the UPDATE privilege for it. This means you can use a trigger to modify the values to be inserted into a new row or used to update a row. (Such a SET statement has no effect in an AFTER trigger because the row change will have already occurred.)...

話雖這麼說,你的觸發器應該像

CREATE TRIGGER percentcalc 
BEFORE UPDATE ON project 
FOR EACH ROW 
    SET NEW.percent = (NEW.fund/NEW.goal) * 100; 

這裏是SQLFiddle演示

+0

@AhmedNassar難道它幫幫我? – peterm