This is a read-only copy of the MariaDB Knowledgebase generated on 2024-11-14. For the latest, interactive version please visit https://mariadb.com/kb/.

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

描述说明

CASE 语句的出现,实现了在存储过程编写复杂条件的要求。如果查询条件为真,那么会执行then代码块的语句。如果没有符合条件的情况,则会执行ELSE语句下的部分。每个 statement_list 都有一个或者是多个sql语句。

如果没有找到条件为真的判断,而且CASE语句也没有else部分,则会返回错误信息。

每个statement_list都是由一个或者多个以;结尾的语句组成的,且不能为空。为了处理不允许为空的情况,可以参考下面这个例子。

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;
|

The indentation used here in the ELSE clause is for purposes of clarity only, and is not otherwise significant. See Delimiters in the mysql client for more on the use of the delimiter command.

注意: 在存储过程中使用case语句格式有别于在http://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html.中的描述。这里说的##CASE 不能以else null 作为判断条件,而且是以END CASE 结尾,而非END

Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.