將空值轉換為實際值
創建測試用表:
CREATE OR REPLACE VIEW v AS
SELECT NULL AS c1, NULL AS c2, '1' AS c3, NULL AS c4, '2' AS c5 FROM dual
UNION ALL
SELECT NULL AS c1, NULL AS c2, NULL AS c3, '3' AS c4, '2' AS c5 FROM dual;
SELECT * FROM v;
如果要查詢列c3的值,當c3列為空時,把它顯示為0,有以下兩種方式:
-- 使用nvl函數
SELECT NVL(c3, '0') c3 FROM v;
-- 使用coalesce函數
SELECT COALESCE(c3, '0') c3 FROM v;
查詢結果如下:
如果要查詢列c1到c5中,第一個不為空的值,也有下面的兩種方式:
-- 方法一
SELECT NVL(NVL(NVL(NVL(c1, c2), c3), c4), c5) AS c from v;
-- 方法二
SELECT COALESCE(c1, c2, c3, c4, c5) AS c FROM v;
查詢結果如下:
可以看到,相對於nvl來說,coalesce支持多個參數,能很方便的返回第一個不為空的值。