mysql> help case operator
CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN
result ...] [ELSE result] END
CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]
[ELSE result] END
Examples:
mysql> SELECT CASE 1 WHEN 1 THEN 'one'
-> WHEN 2 THEN 'two' ELSE 'more' END;
-> 'one'
mysql> SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END;
-> 'true'
mysql> SELECT CASE BINARY 'B'
-> WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;
-> NULL
mysql> help 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表达式和case语句在性质上不一样,但是使用它们的思路是一样的。CASE value WHEN...只能与value进行等同性检查,case when ... then...则要灵活的多。
case operator的使用示例:
MariaDB [test]> select * from Student;
+------+----------+------+--------+
| sid | name | age | class |
+------+----------+------+--------+
| 1 | chenyi | 22 | Java |
| 2 | huanger | 23 | Python |
| 3 | zhangsan | 21 | Java |
| 4 | lisi | 20 | C# |
| 5 | wangwu | 21 | Python |
| 6 | zhaoliu | 19 | Java |
| 7 | qianqi | 22 | C |
| 8 | sunba | 20 | C++ |
| 9 | yangjiu | 24 | Java |
+------+----------+------+--------+
MariaDB [test]> select name,case when age>21 then 'older' else 'younger' end as oy from Student;
+----------+---------+
| name | oy |
+----------+---------+
| chenyi | older |
| huanger | older |
| zhangsan | younger |
| lisi | younger |
| wangwu | younger |
| zhaoliu | younger |
| qianqi | older |
| sunba | younger |
| yangjiu | older |
+----------+---------+
case statement的使用示例:
DELIMITER $$
CREATE OR REPLACE PROCEDURE proc1(a INT,OUT i INT)
BEGIN
CASE
WHEN a>0 THEN
SET @a1=a+100;
WHEN a=0 THEN
SET @a1=a+200;
ELSE
SET @a1=a+300;
END CASE;
SET i=@a1;
END$$
DELIMITER ;
-- 调用存储过程进行测试
CALL proc1(1,@x);
CALL proc1(0,@y);
CALL proc1(-1,@z);
-- 查看测试结果
SELECT @x,@y,@z;
@x @y @z
------ ------ --------
101 200 299
loop是循环,leave是跳出整个循环(类似于break),iterate是跳出当前循环进入下一个循环(类似于continue)。
[begin_label:] LOOP
statement_list
END LOOP [end_label]
在loop结构中,使用end loop关键字作为结束标记。