Search code examples
mysqlstored-proceduresmysql-routines

mysql procedure error in IF..THEN statement


So I have this procedure to calculate freights. I need to select two values from matching row. And according to condition based on in_quantity, out of these two previously selected values one will be set to 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 ;

When executed it gives following error -

#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 

Solution

  • beacause any value assign to a variable in mysql , we use SET keyword. so change only in procedure

    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 ;