CASE expressions can act as the "IF...ELSE...THEN" logic with no need to invoke a subprogram. CASE expressions have two forms: simple and searched.
- Example: Using a simple CASE expression in a query to convert country codes into full country names
obclient> CREATE TABLE t_case(id number NOT NULL PRIMARY KEY, abbr varchar(5));
Query OK, 0 rows affected (0.06 sec)
obclient> INSERT INTO t_case(id, abbr) VALUES (1,'US'),(2,'UK'),(3,'CN'),(4,'JP');
Query OK, 4 rows affected (0.03 sec)
Records: 4 Duplicates: 0 Warnings: 0
obclient>
obclient> SELECT id, abbr,
CASE abbr
WHEN 'US' THEN 'America'
WHEN 'UK' THEN 'English'
WHEN 'CN' THEN 'China'
ELSE 'UNKOWN'
END full_name
FROM t_case ;
+----+------+-----------+
| ID | ABBR | FULL_NAME |
+----+------+-----------+
| 1 | US | America |
| 2 | UK | English |
| 3 | CN | China |
| 4 | JP | UNKOWN |
+----+------+-----------+
4 rows in set (0.00 sec)
obclient>
- Example: Using a searched CASE expression in a query
obclient> CREATE TABLE t_case2(id number NOT NULL PRIMARY KEY, c_date date );
Query OK, 0 rows affected (0.07 sec)
obclient> INSERT INTO t_case2(id,c_date)
VALUES (1,to_date('2019-03-01','yyyy-mm-dd'))
,(2,to_date('2019-05-08','yyyy-mm-dd'))
,(3,to_date('2019-07-07','yyyy-mm-dd'))
,(4,to_date('2019-10-11','yyyy-mm-dd'))
,(5,to_date('2019-12-12','yyyy-mm-dd'))
,(6,to_date('2020-01-05','yyyy-mm-dd'));
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0
obclient> SELECT id, c_date,
CASE
WHEN months_between(sysdate, c_date) > 12 THEN 'More than one year ago'
WHEN months_between(sysdate, c_date) > 9 THEN 'More than three quarters ago'
WHEN months_between(sysdate, c_date) > 6 THEN 'More than half a year ago'
WHEN months_between(sysdate, c_date) > 3 THEN 'More than a quarter ago'
WHEN months_between(sysdate, c_date) >= 0 THEN 'Within a quarter'
ELSE 'Illegal'
END "Duration"
FROM t_case2;
+----+-----------+------------------------------+
| ID | C_DATE | Duration |
+----+-----------+------------------------------+
| 1 | 01-MAR-19 | More than one year ago |
| 2 | 08-MAY-19 | More than three quarters ago |
| 3 | 07-JUL-19 | More than half a year ago |
| 4 | 11-OCT-19 | More than a quarter ago |
| 5 | 12-DEC-19 | More than a quarter ago |
| 6 | 05-JAN-20 | Within a quarter |
+----+-----------+------------------------------+
6 rows in set (0.00 sec)
obclient>