创建测试用表:
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支持多个参数,能很方便的返回第一个不为空的值。
时间: 2024-10-18 05:03:01