调试经验——Oracle 使用NVL函数进行包含空值的列的筛选(Filtering of field values contaning Null value)

在Oracle数据库查询中,遇到因字段为空导致的数据查询不全问题。通过使用NVL函数将空值转换为指定默认值,解决了包含NULL值时查询语句无法正常工作的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

在原来的查询语句(query)中,包含了类似 SAMPLETABLE.SAMPLEFIELD NOT IN ('EXCLUEDED VALUE1','EXCLUEDED VALUE2')这样的条件,结果是,当一条数据的SAMPLEFIELD为空时,该条数据查不出来。


经过近一小时的调试,才找到了解决办法:

使用NVL函数封装该字段后再进行判断,即NVL(SAMPLETABLE.SAMPLEFIELD,0) NOT IN ('EXCLUEDED VALUE1','EXCLUEDED VALUE2')


分析:当Null值与任何值进行比较时,返回的结果都是Null,所以要将Null值转换为一个非Null的值再进行字符串的比较。


Oracle_Database_SQL_Language_Reference_11.2中对NVL函数的讲解如下:

--------------------------------------------------------------------------------------------------

Purpose
NVL lets you replace null (returned as a blank) with a string in the results of a query. If
expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL returns expr1.
The arguments expr1 and expr2 can have any data type. If their data types are
different, then Oracle Database implicitly converts one to the other. If they cannot be
converted implicitly, then the database returns an error. The implicit conversion is
implemented as follows:
1. If expr1 is character data, then Oracle Database converts expr2 to the data type of
expr1 before comparing them and returns VARCHAR2 in the character set of expr1.
2. If expr1 is numeric, then Oracle Database determines which argument has the
highest numeric precedence, implicitly converts the other argument to that data
type, and returns that data type.

Examples
The following example returns a list of employee names and commissions,
substituting "Not Applicable" if the employee receives no commission:
SELECT last_name, NVL(TO_CHAR(commission_pct), 'Not Applicable') commission
FROM employees
WHERE last_name LIKE 'B%'
ORDER BY last_name;
LAST_NAME COMMISSION
------------------------- ----------------------------------------
Baer  Not Applicable
Baida  Not Applicable
Banda  .1
Bates  .15
Bell  Not Applicable
Bernstein  .25
Bissot  Not Applicable
Bloom  .2
Bull  Not Applicable


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值