SQL模糊查询碰到空值怎么办?

SQL查询语句用%来做模糊查询,程序中一般要求用户输入部分信息,根据这个信息进行模糊查询。例如用户输入340104,下面这条语句就是查询昨天客户代码为340104开头的所有邮件信息:

[sql]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. select *  from tb_evt_mail_clct t  
  2.  where t.clct_date = trunc(sysdate - 1)  
  3.    and t.sender_cust_code like '340104%'  

当用户什么都不输入需要查询昨天所有邮件信息时,下面的语句并不能查询到所有信息,这条语句只能查到所有大客户的邮件信息,查不到散户的邮件信息:

[sql]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. select *  from tb_evt_mail_clct t  
  2.  where t.clct_date = trunc(sysdate - 1)  
  3.    and t.sender_cust_code like '%'  

这是因为散户的客户代码为空值,下面这条语句可以同时兼顾上面两种情形(假定用0000代表空值):

有限定值:

[sql]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. select *  from tb_evt_mail_clct t  
  2.  where t.clct_date = trunc(sysdate - 1)  
  3.    and nvl(t.sender_cust_code,'0000'like '340104%'  

无限定值:

[sql]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. select *  from tb_evt_mail_clct t  
  2.  where t.clct_date = trunc(sysdate - 1)  
  3.    and nvl(t.sender_cust_code,'0000'like '%'  

限定值是0000时结果是所有散户:

[sql]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. select *  from tb_evt_mail_clct t  
  2.  where t.clct_date = trunc(sysdate - 1)  
  3.    and nvl(t.sender_cust_code,'0000'like '0000%'  

除了like,not like、not in 、<>等运算符号也都不包含空值,例如下面语句并不包含客户代码为空值的记录:

[sql]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. select *  from tb_evt_mail_clct t  
  2.  where t.clct_date = trunc(sysdate - 1)  
  3.    and t.sender_cust_code <> '34122600200300'  

要想包含,同样需要将条件改为:nvl(t.sender_cust_code,'0000') <> '34122600200300'

总之,当一个字段为空值时,表达式中无论是等于还是不等于,结果都为假,只有 is null结果为真。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值