mysql case实例:在存储过程中使用CASE WHEN条件

发布时间:2019-11-16编辑:脚本学堂
本文介绍下,mysql中case语句的一个例子,在存储过程中使用case when语句的参考示例,有需要的朋友,可以看看。

学习mysql中case when语句的用法,代码如下:

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';
    ->
    ->          WHEN id > 5 THEN
    ->               select 'greater than 5';
    ->
    ->     END CASE;
    -> END$$
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call myProc(2); //调用存储过程myProc
ERROR 1339 (20000): Case not found for CASE statement
mysql> call myProc(20);
+----------------+
| greater than 5 |
+----------------+
| greater than 5 |
+----------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

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