Oracle中Decode 函式使用技巧

2021-05-24 02:38:30 字數 3409 閱讀 7336

oracledecode()函式使用技巧

decode

函式是oracle pl/sql

是功能強大的函式之一,目前還只有

oracle

公司的sql

提供了此函式,其他資料庫廠商的

sql實現還沒有此功能。

decode

有什麼用途呢?

先構造乙個例子,假設我們想給智星職員加工資,其標準是:工資在

8000

元以下的將加

20%;工資在

8000

元以上的加

15%,通常的做法是,先選出記錄中的工資字段值

? select salary into var-salary from employee

,然後對變數

var-salary

用if-then-else

或choose case

之類的流控制語句進行判斷。

如果用decode

函式,那麼我們就可以把這些流控制語句省略,通過

sql語句就可以直接完成。如下:

select decode(sign(salary - 8000),1,salary*1.15,-1,salary*1.2,salary from employee

是不是很簡潔?

decode

的語法:

decode(value,if1,then1,if2,then2,if3,then3,...,else)

,表示如果

value

等於if1

時,decode

函式的結果返回

then1,...,

如果不等於任何乙個

if值,則返回

else

。初看一下,

decode

只能做等於測試,但剛才也看到了,我們通過一些函式或計算替代

value

,是可以使

decode

函式具備大於、小於或等於功能。

decode()

函式使用技巧

·軟體環境:1

、windows nt4.0+oracle 8.0.42、

oracle

安裝路徑為

:c:/orant

·含**釋

: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

· 使用方法:1

、比較大小

select decode(sign(

變數1-

變數2),-1,

變數1,

變數2) from dual; --

取較小值

sign()

函式根據某個值是

0、正數還是負數,分別返回0、

1、-1例如:變數

1=10

,變數2=20

則sign(

變數1-

變數2)

返回-1

,decode

解碼結果為「變數

1」,達到了取較小值的目的。

2、表、檢視結構轉化

現有乙個商品銷售表

sale

,表結構為

:month

char(6)

--月份

sell

number(10,2)

--月銷售金額

現有資料為

:200001

1000

200002

1100

200003

1200

200004

1300

200005

1400

200006

1500

200007

1600

200101

1100

200202

1200

200301

1300

想要轉化為以下結構的資料

:year

char(4)

--年份

month1

number(10,2)

--1月銷售金額

month2

number(10,2)

--2月銷售金額

month3

number(10,2)

--3月銷售金額

month4

number(10,2)

--4月銷售金額

month5

number(10,2)

--5月銷售金額

month6

number(10,2)

--6月銷售金額

month7

number(10,2)

--7月銷售金額

month8

number(10,2)

--8月銷售金額

month9

number(10,2)

--9月銷售金額

month10

number(10,2)

--10

月銷售金額

month11

number(10,2)

--11

月銷售金額

month12

number(10,2)

--12

月銷售金額

結構轉化的

sql語句為

:create or replace view

v_sale(year,month1,month2,month3,month4,month5,month6,month7,month8,month9,month10,month11,month12)

asselect

substrb(month,1,4),

sum(decode(substrb(month,5,2),'01',sell,0)),

sum(decode(substrb(month,5,2),'02',sell,0)),

sum(decode(substrb(month,5,2),'03',sell,0)),

sum(decode(substrb(month,5,2),'04',sell,0)),

Oracle 中 decode 函式用法

含 釋 decode 條件,值1,返回值1,值2,返回值2,值n,返回值n,預設值 該函式的含義如下 if 條件 值1 then return 翻譯值1 elsif 條件 值2 then return 翻譯值2 elsif 條件 值n then return 翻譯值n else return 預設值...

Oracle 中 decode 函式用法

含 釋 decode 條件,值1,返回值1,值2,返回值2,值n,返回值n,預設值 該函式的含義如下 if 條件 值1 then return 翻譯值1 elsif 條件 值2 then return 翻譯值2 elsif 條件 值n then return 翻譯值n else return 預設值...

Oracle 中 decode 函式用法

含 釋 decode 條件,值1,返回值1,值2,返回值2,值n,返回值n,預設值 該函式的含義如下 if 條件 值1 then return 翻譯值1 elsif 條件 值2 then return 翻譯值2 elsif 條件 值n then return 翻譯值n else return 預設值...