我試圖計算百分比列在我的表project
更新後發生在下列任何一欄fund
和goal
的。MYSQL觸發器來計算百分比
這是我做了查詢:
CREATE TRIGGER percentcalc AFTER UPDATE ON project
FOR EACH ROW
SET percent = (fund/goal) *100
但我似乎得到一個錯誤:
#1193 - Unknown system variable 'percent'
我試圖計算百分比列在我的表project
更新後發生在下列任何一欄fund
和goal
的。MYSQL觸發器來計算百分比
這是我做了查詢:
CREATE TRIGGER percentcalc AFTER UPDATE ON project
FOR EACH ROW
SET percent = (fund/goal) *100
但我似乎得到一個錯誤:
#1193 - Unknown system variable 'percent'
delimiter //
CREATE TRIGGER percentcalc AFTER UPDATE ON project
FOR EACH ROW BEGIN
SET NEW.percent = (NEW.fund/NEW.goal) * 100;
END
//
delimiter ;
主要有兩大問題:
NEW
關鍵字來訪問行的列的值正在更新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演示
@AhmedNassar難道它幫幫我? – peterm