13.6.5.1 CASE Statement语句

CASE case_value
    WHEN when_value THEN statement_list
    [WHEN when_value THEN statement_list] ...
    [ELSE statement_list]
END CASE

Or:或:

CASE
    WHEN search_condition THEN statement_list
    [WHEN search_condition THEN statement_list] ...
    [ELSE statement_list]
END CASE

The CASE statement for stored programs implements a complex conditional construct.存储程序的CASE语句实现了一个复杂的条件构造。

Note注意

There is also a CASE operator, which differs from the CASE statement described here. 还有一个CASE运算符,它与这里描述的CASE语句不同。See Section 12.5, “Flow Control Functions”. 请参阅第12.5节,“流程控制函数”The CASE statement cannot have an ELSE NULL clause, and it is terminated with END CASE instead of END.CASE语句不能有ELSE NULL子句,并且它以END CASE而不是END终止。

For the first syntax, case_value is an expression. 对于第一种语法,case_value是一个表达式。This value is compared to the when_value expression in each WHEN clause until one of them is equal. 将此值与每个WHEN子句中的when_value表达式进行比较,直到其中一个相等。When an equal when_value is found, the corresponding THEN clause statement_list executes. 当找到等于when_value时,将执行相应的THEN子句statement_listIf no when_value is equal, the ELSE clause statement_list executes, if there is one.如果没有when_value相等,则执行ELSE子句statement_list(如果有)。

This syntax cannot be used to test for equality with NULL because NULL = NULL is false. 此语法不能用于测试是否与NULL相等,因为NULL=NULLfalseSee Section 3.3.4.6, “Working with NULL Values”.请参阅第3.3.4.6节,“使用NULL值”

For the second syntax, each WHEN clause search_condition expression is evaluated until one is true, at which point its corresponding THEN clause statement_list executes. 对于第二种语法,每个WHEN子句search_condition表达式都被求值,直到有一个表达式为true,此时执行相应的THEN子句statement_listIf no search_condition is equal, the ELSE clause statement_list executes, if there is one.如果没有search_condition相等,则执行ELSE子句statement_list(如果有)。

If no when_value or search_condition matches the value tested and the CASE statement contains no ELSE clause, a Case not found for CASE statement error results.如果没有when_valuesearch_condition与测试的值匹配,并且CASE语句不包含ELSE子句,则产生错误结果Case not found for CASE statement

Each statement_list consists of one or more SQL statements; an empty statement_list is not permitted.每个statement_list由一个或多个SQL语句组成;不允许使用空statement_list

To handle situations where no value is matched by any WHEN clause, use an ELSE containing an empty BEGIN ... END block, as shown in this example. 若要处理没有值与任何WHEN子句匹配的情况,请使用包含空BEGIN ... END块的ELSE,如本例所示。(The indentation used here in the ELSE clause is for purposes of clarity only, and is not otherwise significant.)(此处在ELSE子句中使用的缩进仅为清楚起见,在其他方面并不重要。)

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN
        END;
    END CASE;
  END;
  |