mysql case实例:CASE WHEN with ELSE的用法

发布时间:2020-11-12编辑:脚本学堂
本文介绍下,mysql中有关case语句的一个实例,学习下case when中else的用法,有需要的朋友参考下吧。

本节学习下mysql中case when else的用法,代码如下:

mysql> delimiter $$
mysql> CREATE PROCEDURE myProc(id int) //创建mysql存储过程
    -> BEGIN
    ->     CASE
    ->          WHEN id < 2  THEN
    ->               select 'less than 2';
    ->          WHEN id > 2 and id < 5 THEN
    ->               select 'greater than 2 and less than 5';
    ->          ELSE
    ->               select 'ELSE';
    ->     END CASE;
    -> END$$
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call myProc(1); //调用存储过程
+-------------+
| less than 2 |
+-------------+
| less than 2 |
+-------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

mysql>
mysql> call myProc(3); //调用存储过程
+--------------------------------+
| greater than 2 and less than 5 |
+--------------------------------+
| greater than 2 and less than 5 |
+--------------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> drop procedure myProc; //删除存储过程
Query OK, 0 rows affected (0.00 sec)