首页 > 解决方案 > 关于 nvarchar2 工作问题的 Oracle 12 等于和不等于 (=, !=, <>) 行为

问题描述

在 oracle 中,空 varchar2 和 null 被视为相同,因为 Oracle 在内部将空字符串更改为 NULL 值。请考虑以下示例:

--1- create table
CREATE TABLE persons(
    person_id NUMBER GENERATED BY DEFAULT AS IDENTITY,
    first_name VARCHAR2(50)  ,
    last_name VARCHAR2(50)  ,
    PRIMARY KEY(person_id)
); 

--2-insert sample data
insert into persons (first_name,last_name) values('n1','l1');
insert into persons (first_name,last_name) values('n2',null);
insert into persons (first_name,last_name) values('n3','');
insert into persons (first_name) values('n4'); 

以下查询有结果:

select * from persons where last_name is null;

PERSON_ID FIRST_NAME      LAST_NAME                                        
    2      n2                                                                                                   
    3      n3                                                                                                   
    4      n4       

 select * from persons where last_name is not null;
    PERSON_ID FIRST_NAME       LAST_NAME                          
        1      n1                  l1     

我的问题 :

1-为什么这个查询结果是“没有选择行”</p>

select * from persons where last_name =''; --   no rows selected
select * from persons where last_name !=''; --  no rows selected

2-更重要的问题是以下查询的精彩行为:

select * from persons where last_name !='' or last_name =''; --  no rows selected

标签: oraclenullvarchar2

解决方案


1-为什么这个查询结果是“没有选择行”</p>

因为答案在于你的问题本身。

select * from persons where last_name =''; -- here '' is converted to NULL
-- so last_name = NULL 
-- it will always fail as NULL can not match with other NULL also

select * from persons where last_name !=''; --  - here '' is converted to NULL
-- so last_name != NULL 
-- it will always fail as NULL can not mismatch with other NULL also

2-更重要的问题是以下查询的精彩行为:

select * from persons where last_name !='' or last_name =''; 
--  equal or not equal with NULL will always return false. 
-- so the result is no rows for this query also

请注意,在任何表达式中,如果一侧是NULL,它将始终返回 false。(IS NULLIS NOT NULL需要用于检查空值)


推荐阅读