我正在尝试编写一个触发器,将表中的所有条目从1到10排列(最大值具有等级10,最小值具有等级1,所有其他值都被赋予其间的整数值)。这是触发器代码:
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),其中slope = 9 /(maxval - minval)。
答案 0 :(得分:1)
你应该检查一个超出范围的例外。它永远不应该等于0.如果它确实会查询失败并填满数据库。
在将maxval
设置为minval
<之前,您应该检查maxval - minval
和0
以确保slope
不等于9/(maxval - minval)
/ p>
如果你运行这个
SET slope = 9 / (max_cost – min_cost);
并尝试将slope
设置为9/0
它会崩溃。
答案 1 :(得分:1)
我不熟悉触发器,但我认为您的问题出在SET
声明中。
我在想你不能设置NEW.priority_monetary
我之前没有看到任何类似SQL的语法,但我仍然是游戏的新手,但我猜你如果放弃NEW.
而只是设置priority_monetary
那么错误可能会消失