Term: DECODE
Definition:
The DECODE function is analogous to the "IF THEN ELSE" conditional statement. DECODE works with values, columns, and expressions of all data types.
Example Syntax:
The DECODE function is analogous to the "IF THEN ELSE" conditional statement. DECODE works with values, columns, and expressions of all data types.
Example Syntax:
DECODE (expression, search, result [, search, result]... [, default])
The DECODE function compares expression against each search value in order. If a match (equality) is found between the expression and the search argument then it returns the corresponding result. If there is no match, the default value is returned (if defined), else it returns NULL. In case of a type compatibility mismatch, Oracle internally does an implicit conversion (if possible) to return the results.
Interestingly, Oracle considers two NULLs to be equivalent while working with the DECODE function.
Interestingly, Oracle considers two NULLs to be equivalent while working with the DECODE function.
SQL> SELECT DECODE(NULL,NULL,'EQUAL','NOT EQUAL') FROM DUAL;
DECODE
-----
EQUAL
If expression is NULL, then Oracle returns the result of the first search that is also NULL. The maximum number of components in the DECODE function, including expression, searches, results, and default, is 255.
SQL> SELECT EMPLOYEE_NAME, SALARY, DECODE (HIRE_DATE, SYSDATE,'NEW JOINEE','EMPLOYEE')
FROM EMPLOYEES
---------------------------------------------------------------------
http://blog.itcert.org/archives/902
Oracle數據庫Decode函數的使用方法
DECODE函數的作用:它可以將輸入數值與函數中的參數列表相比較,根據輸入值返回一個對應值。函數的參數列表是由若干數值及其對應結果值組成的若干序偶形式。當然,如果未能與任何一個實參序偶匹配成功,則函數也有默認的返回值。
區別於SQL的其它函數,DECODE函數還能識別和操作空值。
語法如下:
DECODE(control_value,value1,result1[,value2,result2…][,default_result]);
control _value
試圖處理的數值。 DECODE函數將該數值與後面的一系列的偶序相比較,以決定返回值。
value1
是一組成序偶的數值。如果輸入數值與之匹配成功,則相應的結果將被返回。對應一個空的返回值,可以使用關鍵字NULL於之對應
result1
是一組成序偶的結果值。
default_result未能與任何一個值匹配時,函數返回的默認值。
示例如下:
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’。
在需要比較2個值的時候,我們可以配合SIGN()函數一起使用。
SELECT DECODE( SIGN(5 -6), 1 ‘Is Positive’, -1, ‘Is Nagative’, ‘Is Zero’)
同樣,也可以用CASE實現:
SELECT CASE SIGN(5 – 6)
WHEN 1 THEN ‘Is Positive’
WHEN-1 THEN ‘Is Nagative’
ELSE’Is Zero’ END
FROM DUAL
另外,大家還可以在Order by中使用Decode。
例:表table_subject,有subject_name列。要求按照:語、數、外的順序進行排序。這時,就可以非常輕鬆的使用Decode完成要求了。
select * from table_subject order by decode(subject_name, ‘語文’, 1, ‘數學’, 2, , ‘外語’,3)
沒有留言:
張貼留言