你的位置:首页 > 数据库

[数据库]将空值转换为实际值


创建测试用表:

CREATE OR REPLACE VIEW v ASSELECT NULL AS c1, NULL AS c2, '1' AS c3, NULL AS c4, '2' AS c5 FROM dualUNION ALLSELECT 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支持多个参数,能很方便的返回第一个不为空的值。