2014-01-13 73 views
1

我想寫一個觸發器,將表中所有條目從1到10進行排序(最大值爲10,最小值爲1,所有其他都在其間賦值爲整數值)。下面是觸發代碼:這個MySQL觸發器有什麼問題?

DELIMITER $$ 
CREATE TRIGGER risks_before_insert 
BEFORE INSERT ON risks 
FOR EACH ROW 
BEGIN 

DECLARE max_cost double; #previous maximum expected_cost in project 
DECLARE min_cost double; #previous minimum expected_cost in project 
DECLARE slope double; #slope for prioritizing functioN 

SELECT MAX(expected_cost), MIN(expected_cost) INTO max_cost, min_cost FROM view_risks; #GET EXTREME VALUES FROM TABLE, STORE IN MEMORY 

/* 
Update Priority Monetary Rankings 
*/ 
IF (max_cost IS NULL OR min_cost IS NULL) THEN #check for empty table 
    SET NEW.priority_monetary = 10; 
ELSE IF ((NEW.expected_cost <= max_cost) AND (NEW.expected_cost >= min_cost)) THEN #NEW VALUE DOES NOT CHANGE TABLE EXTREMES 
    IF (max_cost – min_cost = 0) THEN 
     SET NEW.priority_monetary = 10; 
    ELSE 
     SET slope = 9/(max_cost – min_cost); 
     SET NEW.priority_monetary = slope * (NEW.expected_cost - min_cost) + 1; 
    END IF; 
ELSE IF (NEW.expected_cost > max_cost) THEN 
    SET NEW.priority_monetary = 10; 
    SET slope = 9/(NEW.expected_cost – min_cost); 
    UPDATE TABLE risks SET priority_monetary = slope * (expected_cost - min_cost) + 1; 
ELSE #NEW VALUE CORRESPONDS TO A MINIMUM 
    SET NEW.priority_monetary = 1; 
    SET slope = 9/(max_cost – NEW.expected_cost); 
    UPDATE TABLE risks SET priority_monetary = slope * (expected_cost – NEW.min_cost) + 1; 
END IF; 
END $$ 
DELIMITER ; 

不過,我收到以下錯誤:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '– min_cost); SET NEW.priority_monetary = slope * (NEW.expected_cost - min_cost' at line 22 

誰能解釋一下什麼是錯的?供大家參考,我的排名算法是由下面的函數與常量MAXVAL和MINVAL描述:

Rank(x) = 1 + slope(x - minval), where slope = 9/(maxval - minval).

+0

您的縮進也是關閉的,這並不會使讀起來有趣。請修正縮進,**這裏和在您的機器上的代碼** – Malachi

+1

我的機器上的縮進是正確的。我不確定爲什麼當我在這裏發佈它時會搞砸,但我已經修復了它。 – Paul

+0

什麼數據類型是'priority_monetary'?當你執行乘法時,它返回一個'BIGINT' – Malachi

回答

1

你應該檢查超出範圍異常。它不應該等於0.如果這樣做,查詢將會失敗並將數據庫連接起來。

你應該檢查maxvalminval確保maxval - minval不等於0之前設置slope9/(maxval - minval)

如果運行此

SET slope = 9/(max_cost – min_cost); 

,並試圖爲slope9/0它會崩潰。

+0

謝謝,我做了這個修正。我仍然得到相同的錯誤。我已經更新了上面的代碼。 – Paul

+0

錯誤消息已更改。你應該看看發佈一個新的問題,也許 – Malachi

1

我不熟悉觸發器,但我認爲你的問題在SET聲明中。

我認爲你不能設置NEW.priority_monetary

我以前從未見過任何類似語法,對於SQL,但我還是新的遊戲,但我猜測,即使你刪除掉NEW.和公正設置爲priority_monetary那麼錯誤可能會消失

+1

你可以像這樣設置,實際上你必須否則它將被評估爲布爾條件。看到這裏的例子:http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html – Paul