天天看點

Oracle中coalesce函數的用法

學習了幾天教主的書,今天看到coalesce函數,功能很強大啊!

coalesce函數的參數是列,結果是取出第一個不為空的列的資料。

首先,建一個視圖:

CREATE OR REPLACE VIEW v AS SELECT NULL AS c1,NULL AS c2,1 AS c3,NULL AS c4,2 AS c5,NULL AS c6 FROM dual UNION ALL SELECT NULL AS c1,NULL AS c2,NULL AS c3,3 AS c4,NULL AS c5,2 AS c6 FROM dual;
           

檢視視圖結果:

Oracle中coalesce函數的用法

使用coalesce函數查結果:

SELECT COALESCE (c1,c2,c3,c4,c5,c6) AS c FROM v;
           

結果竟是:

Oracle中coalesce函數的用法

難道coalesce函數不支援number類型?帶着這個疑問,給轉換一下,結果:

SELECT COALESCE (c1,c2,to_char(c3),to_char(c4),to_char(c5),to_char(c6)) AS c FROM v;
           
Oracle中coalesce函數的用法

好像是真的,那麼對date類型的支援呢?試一試

CREATE OR REPLACE VIEW v AS
SELECT to_date('20150101','YYYYMMDD') AS c1,NULL AS c2,1 AS c3,NULL AS c4,2 AS c5,NULL AS c6 FROM dual
UNION ALL
SELECT NULL AS c1,NULL AS c2,NULL AS c3,3 AS c4,NULL AS c5,2 AS c6 FROM dual;
           

結果竟然:

Oracle中coalesce函數的用法

到這裡就不禁要想,應該不是不支援某種資料類型,而是把第一列的資料類型,作為整個函數的資料類型了。

這樣試試就行了

Oracle中coalesce函數的用法

最後,既然coalesce函數裡面是列,那麼用*代表所有列行不行呢?

Oracle中coalesce函數的用法

顯然是不行的。

總結:

1、coalesce函數是用來擷取第一個不為空的列的值

2、coalesce函數裡面的資料類型,必須全部都跟第一列的資料類型一緻

3、CREATE OR REPLACE VIEW v AS SELECT NULL AS c FROM dual;這樣建立的視圖,列c的資料類型是char。