Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF statement in MySQL stored function goes wrong

I get a error on line 12 (at the endif statement). I belief I´m doing something wrong within the IF or ELSE, can anyone help me?

DELIMITER $$

CREATE FUNCTION TEST (`param` INT) 
RETURNS INT 
DETERMINISTIC
BEGIN
    DECLARE `var` INT;

    SET `var` = 1;

    IF `param` > 0 THEN
        SET `var` = `var` + `param`;
    END IF;

    RETURN `var`;
END$$

EDIT: (same function with case instead of if, same problem)

DELIMITER $$

CREATE FUNCTION TEST (`param` INT) 
RETURNS INT 
DETERMINISTIC
BEGIN
    DECLARE `var` INT;

    SET `var` = 1;

    SET `var` = 
        CASE
            WHEN `param` > 0 THEN `var` + `param` ELSE `var`
        END ;

    RETURN `var`;
END$$
like image 599
pascalvgemert Avatar asked Feb 20 '23 01:02

pascalvgemert


1 Answers

Try this instead:

BEGIN
    DECLARE `var` INT;

    SET var = 
      CASE
        WHEN param > 0 THEN var + 1 ELSE var 
      END ;

    RETURN var;
END$$
like image 90
Mahmoud Gamal Avatar answered Feb 22 '23 01:02

Mahmoud Gamal