1.第一種用法:可以稱為簡單變數;
SELECT ename,
(CASE deptno
WHEN 10 THEN 'ACCOUNTING'
WHEN 20 THEN 'RESEARCH'
WHEN 30 THEN 'SALES'
WHEN 40 THEN 'OPERATIONS'
ELSE 'Unassigned'
END ) as Department
FROM emp;
ENAME DEPARTMENT
---------- ----------
SMITH RESEARCH
ALLEN Unassigned
WARD SALES
JONES RESEARCH
MARTIN SALES
BLAKE SALES
CLARK ACCOUNTING
SCOTT RESEARCH
KING ACCOUNTING
TURNER SALES
ADAMS RESEARCH
JAMES SALES
2.第二種用法:可以稱為條件運算式;
SELECT ename, sal, deptno,
CASE
WHEN sal <= 500 then 0
WHEN sal > 500 and sal<1500 then 100
WHEN sal >= 1500 and sal < 2500 and deptno=10 then 200
WHEN sal > 1500 and sal < 2500 and deptno=20 then 500
WHEN sal >= 2500 then 300
ELSE 0
END "bonus"
FROM emp;
ENAME SAL DEPTNO bonus
---------- ---------- ---------- ----------
SMITH 800 20 100
ALLEN 1600 90 0
WARD 1250 30 100
JONES 2975 20 300
MARTIN 1250 30 100
BLAKE 2850 30 300
CLARK 2450 10 200
3.呵呵,在某些情況下,其實也可以使用decode()函數,它和CASE用法可以互換。
比如:select decode( x , 1 , 'x is 1 ’, 2 , 'x is 2 ’, 'others’) from dual
當x等於1時,則返回 'x is 1’。
當x等於2時,則返回 'x is 2’。
否則,返回'others’。
再比如:想判斷a=0時,顯示false,否則顯示true.
可以這樣來寫:decode(a,0,false,true)