IF..THEN语句中的mysql过程错误

时间:2016-02-26 11:02:24

标签: mysql stored-procedures mysql-routines

所以我有这个程序来计算货运。我需要从匹配的行中选择两个值。根据基于in_quantity的条件,在这两个先前选择的值中,一个将设置为out_total

DELIMITER $$
CREATE PROCEDURE freight_calc(
    IN in_delivery_location VARCHAR(100),
    IN in_category_id INT(11),
    IN in_quantity INT(11),   
    OUT out_total DECIMAL(10,2)
    )
BEGIN
    DECLARE val1 DECIMAL(10,2);
    DECLARE val2 DECIMAL(10,2);

    SELECT col1,col2 INTO val1, val2 
    FROM `freight_rules` fr
    WHERE fr.category_id = in_category_id AND fr.delivery_location = in_delivery_location;

    IF(in_quantity <= 9) THEN
        out_total = val1;
    END IF;

    IF(in_quantity > 9) THEN
        out_total = val2;
    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 '= val1;
    END IF;

    IF(in_quantity > 9) THEN
        out_total = val2' at line 16 

1 个答案:

答案 0 :(得分:2)

因为在mysql中为变量分配了任何值,我们使用SET关键字。 所以只在程序中改变

SET out_total = val1;
SET out_total = val1;

DELIMITER $$
CREATE PROCEDURE freight_calc(
    IN in_delivery_location VARCHAR(100),
    IN in_category_id INT(11),
    IN in_quantity INT(11),   
    OUT out_total DECIMAL(10,2)
    )
BEGIN
    DECLARE val1 DECIMAL(10,2);
    DECLARE val2 DECIMAL(10,2);

    SELECT col1,col2 INTO val1, val2 
    FROM `freight_rules` fr
    WHERE fr.category_id = in_category_id AND fr.delivery_location = in_delivery_location;

    IF(in_quantity <= 9) THEN
      SET out_total = val1;
    END IF;

    IF(in_quantity > 9) THEN
       SET out_total = val1;
    END IF;

END$$
DELIMITER ;