Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
DECODE and CASE statements in Oracle both provide a conditional construct, of this form: if A = n1 then A1 else if A = n2 then A2 else X Databases before Oracle 8.1.6 had only the DECODE function. CASE was introduced in Oracle 8.1.6 as a standard, more meaningful and more powerful function. Everything DECODE can do, CASE can. There is a lot else CASE can do though, which DECODE cannot. Well go through detailed examples in this article.
1 2 3 SQL> select e.ename, 2 case 4 3 -- predicate with "in" 5 4 -- mark the category based on ename list 6 5 when e.ename in ('KING','SMITH','WARD') 6 then 'Top Bosses' 7 7 -- searchable subquery 8 8 -- identify if this emp has a reportee 9 9 when exists (select 1 from emp emp1 10 10 where emp1.mgr = e.empno) 11 11 then 'Managers' else 12 12 13 'General Employees' 13 14 end emp_category 14 15 from emp e 15 16 where rownum < 5; 16 EMP_CATEGORY 17ENAME -------------------------18 SMITH Top Bosses 19ALLEN General Employees 20WARD Top Bosses 21JONES Managers 22 23
3 4 PL/SQL procedure successfully completed. 5 6 SQL> SQL> create or replace procedure proc_test (i number) 7 2 as 8 3 begin 4 dbms_output.put_line('output = '||i); 9 10 5 end; 11 6 / 12Procedure created. 13 14SQL> exec proc_test(decode(:a,'THREE',3,0)); 15BEGIN proc_test(decode(:a,'THREE',3,0)); END; 16 * 17 ERROR at line 1: 18 ORA-06550: line 1, column 17: 19PLS-00204: function or pseudo-column 'DECODE' may be used inside a SQL 20statement only 21ORA-06550: line 1, column 7: 22PL/SQL: Statement ignored 23 24 exec proc_test(case :a when 'THREE' then 3 else 0 end); 25SQL> output = 3 26 27PL/SQL procedure successfully completed. 28 29 30 31
8 -------9 NOT NULL 10 The searched CASE works as does DECODE. 1 2 SQL> select case 2 when null is null 3 3 then 'NULL' 4 4 else 'NOT NULL' 5 5 end null_test 6* from dual 6 7 SQL> / 8 NULL_TES 9 -------10NULL 11
4 SQL> select ename 2 , decode (deptno, 10, 'Accounting', 5 3 20, 'Research', 6 4 30, 'Sales', 7 5 'Unknown') as department 8 6 from emp 7 where rownum < 4; 9 10 DEPARTMENT 11ENAME ---------- ---------12SMITH Research 13ALLEN Sales 14WARD Sales 15 16SQL> select ename , case deptno 17 2 3 when 10 then 'Accounting' 18 4 when 20 then 'Research' 19 5 when 30 then 'Sales' 20 6 else 'Unknown' 21 7 end as department 22 8 from emp 23 9 where rownum < 4; 24 ENAME DEPARTMENT 25---------- ---------26SMITH Research Sales 27ALLEN WARD Sales 28 29 30 31 32 33 Complicated logical comparisons in DECODE, even if technically achievable, are a recipe for messy, bug-prone code. When the same can be done more cleanly with CASE, go for CASE.