CASE 语句从一序列的条件里选择并执行相应的语句。

简单 CASE 语句

最简单的 CASE 语句会计算一个单一表达式值并跟多个潜在值进行比较。语法格式如下:

  1. CASE expression
  2. WHEN value THEN statement
  3. [ WHEN value THEN statement ]...
  4. [ ELSE statement [, statement ]... ]
  5. END CASE;

示例:使用简单 CASE 语句

  1. delimiter /
  2. CREATE OR REPLACE PROCEDURE sp_guess_abbr(p_abbr IN varchar)
  3. IS
  4. BEGIN
  5. CASE p_abbr
  6. WHEN 'CN' THEN
  7. dbms_output.put_line('CHINA');
  8. WHEN 'UK' THEN
  9. dbms_output.put_line('ENGLISH');
  10. WHEN 'US' THEN
  11. dbms_output.put_line('AMERICA');
  12. ELSE
  13. dbms_output.put_line('UNKOWN!');
  14. END CASE;
  15. END;
  16. /
  17. delimiter ;
  18. obclient>
  19. obclient> call sp_guess_abbr('UK');
  20. Query OK, 0 rows affected (0.00 sec)
  21. ENGLISH
  22. obclient> call sp_guess_abbr('RU');
  23. Query OK, 0 rows affected (0.01 sec)
  24. UNKOWN!
  25. obclient>

搜索的 CASE 语句

搜索的 CASE 语句中 CASE 后没有表达式要计算,而是 WHEN 后面分别有不同的布尔表达式。搜索的CASE会计算多个布尔表达式并选择第一个结果为 TRUE 的分支。语法格式如下:

  1. CASE
  2. WHEN expression1 THEN statement
  3. [ WHEN expressN THEN statement ]...
  4. [ ELSE statement [, statement ]... ]
  5. END CASE;

示例:使用搜索的 CASE 语句

  1. delimiter /
  2. CREATE OR REPLACE PROCEDURE sp_guess(p_value IN number)
  3. IS
  4. BEGIN
  5. CASE
  6. WHEN p_value > 0 THEN
  7. dbms_output.put_line('The value is a positive number. ');
  8. WHEN p_value < 0 THEN
  9. dbms_output.put_line('The value is a negative number. ');
  10. WHEN p_value = 0 THEN
  11. dbms_output.put_line('The value is zero. ');
  12. ELSE
  13. dbms_output.put_line('The value is NULL. ');
  14. END CASE;
  15. END;
  16. /
  17. delimiter ;
  18. obclient>
  19. obclient> call sp_guess(2020);
  20. Query OK, 0 rows affected (0.04 sec)
  21. The value is a positive number.
  22. obclient> call sp_guess(-2000);
  23. Query OK, 0 rows affected (0.00 sec)
  24. The value is a negative number.
  25. obclient> call sp_guess(NULL);
  26. Query OK, 0 rows affected (0.00 sec)
  27. The value is NULL.
  28. obclient>