Oracle decode函式的使用

2021-08-01 21:17:06 字數 1414 閱讀 5344

今天看別人的sql時看這裡面還有decode()函式,以前從來沒接觸到,上網查了一下,還挺好用的乙個函式,寫下來希望對朋友們有幫助哈!

**:這裡

decode()函式簡介:

主要作用:

將查詢結果翻譯成其他值(即以其他形式表現出來,以下舉例說明);

使用方法:

select decode(columnname,值1,翻譯值1,值2,翻譯值2,…值n,翻譯值n,預設值)

from talbename

where …

其中columnname為要選擇的table中所定義的column,

含**釋:

decode(條件,值1,翻譯值1,值2,翻譯值2,…值n,翻譯值n,預設值)的理解如下:

if (條件==值1)

then    

return(翻譯值1)

elsif (條件==值2)

then    

return(翻譯值2)    

elsif (條件==值n)

then    

return(翻譯值n)

else    

return(預設值)

end if

注:其中預設值可以是你要選擇的column name 本身,也可以是你想定義的其他值,比如other等;

舉例說明:

現定義一table名為output,其中定義兩個column分別為monthid(var型)和sale(number型),若sale值=1000時翻譯為d,=2000時翻譯為c,=3000時翻譯為b,=4000時翻譯為a,如是其他值則翻譯為other;

sql如下:

select monthid,decode(sale,1000,'d',2000,'c',3000,'b',4000,'a',』other』) sale from output

特殊情況:

若只與乙個值進行比較

select monthid ,decode(sale, null,『---』,sale) sale from output

另:decode中可使用其他函式,如nvl函式或sign()函式等;

nvl(expr1,expr2)

若expr1是null,則返回expr2,否則返回expr1.

如果用到decode函式中就是

select monthid,decode(nvl(sale,6000),6000,'ng','ok') from output

sign()函式根據某個值是0、正數還是負數,分別返回0、1、-1,

如果取較小值就是

select monthid,decode(sign(sale-6000),-1,sale,6000) from output即達到取較小值的目的。

oracle decode函式的用法

該函式可以接受可變的引數,具體引數情況如下 decode 條件,值1,翻譯值1,值2,翻譯值2,值n,翻譯值n,預設值 該函式的含義如下 if 條件 值1 return 翻譯值1 else if 條件 值2 return 翻譯值2 else if 條件 值n return 翻譯值n else ret...

oracle decode函式的使用

由於近期的一點點工作,學習了一點點oracle的東西,僅記錄一點 decode函式和sign函式配合在sql語句中做判斷。decode 語法 decode expression,compare1,value1,compare2,value2,defaultvalue 意思很簡單,如果expressi...

Oracle DECODE函式的語法

oracle decode函式功能很強,下面就為您詳細介紹oracle decode函式的用法,希望可以讓您對oracle decode函式有更多的了解。oracle decode函式 oracle decode函式是oracle公司獨家提供的功能,它是乙個功能很強的函式。它雖然不是sql的標準,但...