Searched CASE expression v18
A searched CASE expression uses one or more Boolean expressions to determine the resulting value to return.
Syntax
CASE WHEN <boolean-expression> THEN <result> [ WHEN <boolean-expression> THEN <result> [ WHEN <boolean-expression> THEN <result> ] ...] [ ELSE <result> ] END;
boolean-expressionis evaluated in the order in which it appears in theCASEexpression.resultis an expression that is type-compatible in the context where theCASEexpression is used.- When the first
boolean-expressionis encountered that evaluates toTRUE,resultin the correspondingTHENclause is returned as the value of theCASEexpression. - If none of
boolean-expressionevaluates to true, thenresultfollowingELSEis returned. - If no
ELSEis specified, theCASEexpression returns null.
Example
This example uses a searched CASE expression to assign the department name to a variable based on the department number:
DECLARE v_empno emp.empno%TYPE; v_ename emp.ename%TYPE; v_deptno emp.deptno%TYPE; v_dname dept.dname%TYPE; CURSOR emp_cursor IS SELECT empno, ename, deptno FROM emp; BEGIN OPEN emp_cursor; DBMS_OUTPUT.PUT_LINE('EMPNO ENAME DEPTNO DNAME'); DBMS_OUTPUT.PUT_LINE('----- ------- ------ ----------'); LOOP FETCH emp_cursor INTO v_empno, v_ename, v_deptno; EXIT WHEN emp_cursor%NOTFOUND; v_dname := CASE WHEN v_deptno = 10 THEN 'Accounting' WHEN v_deptno = 20 THEN 'Research' WHEN v_deptno = 30 THEN 'Sales' WHEN v_deptno = 40 THEN 'Operations' ELSE 'unknown' END; DBMS_OUTPUT.PUT_LINE(v_empno || ' ' || RPAD(v_ename, 10) || ' ' || v_deptno || ' ' || v_dname); END LOOP; CLOSE emp_cursor; END;
The following is the output from this program:
Output
EMPNO ENAME DEPTNO DNAME ----- ------- ------ ---------- 7369 SMITH 20 Research 7499 ALLEN 30 Sales 7521 WARD 30 Sales 7566 JONES 20 Research 7654 MARTIN 30 Sales 7698 BLAKE 30 Sales 7782 CLARK 10 Accounting 7788 SCOTT 20 Research 7839 KING 10 Accounting 7844 TURNER 30 Sales 7876 ADAMS 20 Research 7900 JAMES 30 Sales 7902 FORD 20 Research 7934 MILLER 10 Accounting