CASE 表达式可以实现类似“IF…ELSE…THEN”的逻辑而不用调用子程序。CASE 表达式有两种使用方法,简单的和带搜索条件的。

    • 示例:在查询中使用简单的 CASE 表达式,将国家代码缩写翻译为全称。
    1. obclient> CREATE TABLE t_case(id number NOT NULL PRIMARY KEY, abbr varchar(5));
    2. Query OK, 0 rows affected (0.06 sec)
    3. obclient> INSERT INTO t_case(id, abbr) VALUES (1,'US'),(2,'UK'),(3,'CN'),(4,'JP');
    4. Query OK, 4 rows affected (0.03 sec)
    5. Records: 4 Duplicates: 0 Warnings: 0
    6. obclient>
    7. obclient> SELECT id, abbr,
    8. CASE abbr
    9. WHEN 'US' THEN 'America'
    10. WHEN 'UK' THEN 'English'
    11. WHEN 'CN' THEN 'China'
    12. ELSE 'UNKOWN'
    13. END full_name
    14. FROM t_case ;
    15. +----+------+-----------+
    16. | ID | ABBR | FULL_NAME |
    17. +----+------+-----------+
    18. | 1 | US | America |
    19. | 2 | UK | English |
    20. | 3 | CN | China |
    21. | 4 | JP | UNKOWN |
    22. +----+------+-----------+
    23. 4 rows in set (0.00 sec)
    24. obclient>
    • 示例:在查询中使用带搜索条件的 CASE 表达式
    1. obclient> CREATE TABLE t_case2(id number NOT NULL PRIMARY KEY, c_date date );
    2. Query OK, 0 rows affected (0.07 sec)
    3. obclient> INSERT INTO t_case2(id,c_date)
    4. VALUES (1,to_date('2019-03-01','yyyy-mm-dd'))
    5. ,(2,to_date('2019-05-08','yyyy-mm-dd'))
    6. ,(3,to_date('2019-07-07','yyyy-mm-dd'))
    7. ,(4,to_date('2019-10-11','yyyy-mm-dd'))
    8. ,(5,to_date('2019-12-12','yyyy-mm-dd'))
    9. ,(6,to_date('2020-01-05','yyyy-mm-dd'));
    10. Query OK, 6 rows affected (0.01 sec)
    11. Records: 6 Duplicates: 0 Warnings: 0
    12. obclient> SELECT id, c_date,
    13. CASE
    14. WHEN months_between(sysdate, c_date) > 12 THEN 'More than one year ago'
    15. WHEN months_between(sysdate, c_date) > 9 THEN 'More than three quarters ago'
    16. WHEN months_between(sysdate, c_date) > 6 THEN 'More than half a year ago'
    17. WHEN months_between(sysdate, c_date) > 3 THEN 'More than a quarter ago'
    18. WHEN months_between(sysdate, c_date) >= 0 THEN 'Within a quarter'
    19. ELSE 'Illegal'
    20. END "Duration"
    21. FROM t_case2;
    22. +----+-----------+------------------------------+
    23. | ID | C_DATE | Duration |
    24. +----+-----------+------------------------------+
    25. | 1 | 01-MAR-19 | More than one year ago |
    26. | 2 | 08-MAY-19 | More than three quarters ago |
    27. | 3 | 07-JUL-19 | More than half a year ago |
    28. | 4 | 11-OCT-19 | More than a quarter ago |
    29. | 5 | 12-DEC-19 | More than a quarter ago |
    30. | 6 | 05-JAN-20 | Within a quarter |
    31. +----+-----------+------------------------------+
    32. 6 rows in set (0.00 sec)
    33. obclient>