已索引

DECODE 函数专用于 Oracle, 而 CASE 表达式是与 ANSI SQL 兼容的。

语法:
DECODE(col|expression, search1, result1 [, search2, result2,...,][, default])
If the default value is omitted, a null value is returned where a search value does not match any of the result values.

示例:

SELECT last_name, 
       job_id, 
       salary,
       DECODE(job_id, 'IT_PROG',1.10*salary,'ST_CLERK', 1.15*salary,'SA_REP', 1.20*salary,salary) REVISED_SALARY
FROM employees;
SELECT last_name, 
       salary,
       DECODE (TRUNC(salary/2000, 0),
           0, 0.00,
           1, 0.09,
           2, 0.20,
           3, 0.30,
           4, 0.40,
           5, 0.42,
           6, 0.44,
           0.45) TAX_RATE
FROM employees
WHERE department_id = 80;
select decode(1234,123,'123 is a match') 
from dual; 

1234与123做比较,如果相等则返回'123 is a match',但是不等,后面又没有其它比较条件,也没有默认值,所以返回空值。

select decode(1234,123,'123 is a match','no match') 
from dual; 

1234与123做比较,如果相等则返回'123 is a match',但是不等,后面又没有其它比较条件,所以返回默认值'no match'。

select decode('search','comp1','true1','comp2','true2','search','true3',substr('2search',2,6),'true4','false') from dual;

'search'和'comp1'作比较,相等则返回'true1',不等,继续与'comp2'比较,还是不等,继续与'serach'比较,相等,返回'true3',结束,虽然第4个匹配项也匹配search,但是不会计算这个公式,因为在前面的比较项中已经找到了匹配项。

-- By 许望(RHCA、OCM、VCP)
最后修改:2023 年 11 月 08 日 11 : 30 AM
如果觉得我的文章对你有用,请随意赞赏