MySQL Case Select not behaving as expected

后端 未结 2 1762
[愿得一人]
[愿得一人] 2021-01-26 17:01

While creating a more complex stored procedure in MySQL, I encountered a weird problem with my CASE statement. I have simplified my procedure to show the issue. I am selecting t

2条回答
  •  误落风尘
    2021-01-26 17:43

    You're mixing the two ways to use CASE. You either write:

    CASE
        WHEN  THEN ;
        WHEN  THEN ;
        ...
    END CASE
    

    This evaluates each expression, and executes the corresponding result for the first true one. Or:

    CASE 
        WHEN  THEN ;
        WHEN  THEN ;
        ...
    END CASE
    

    This compares to each value, and executes the corresponding result for the first one that matches.

    You used the second syntax, but your values also contain a comparison. So they're all either 0 (for false) or 1 (for true), and that's what you're comparing modTemp to. Change to:

        CASE modTemp
            WHEN 1 THEN
                SELECT 1;
            WHEN 2 THEN
                SELECT 2;
            WHEN 0 THEN
                SELECT 3;
            ELSE
                SELECT CONCAT('Error: modTemp = ', modTemp);
        END CASE;
    

提交回复
热议问题