比较Oracle案例中的字符串何时

时间:2017-01-20 07:24:18

标签: sql oracle case

我遇到了oracle案例的问题。

SELECT CASE WHEN '7C54D3E133830A78E040A8C010014B7D' != ''
            THEN '7C54D3E133830A78E040A8C010014B7D'
            WHEN 'e84a4433966c4b8996ce34905acff63d' != ''
            THEN 'e84a4433966c4b8996ce34905acff63d'
            WHEN '7faa9126b1c6412fa58375ab2b2be1db' != ''
            THEN '7faa9126b1c6412fa58375ab2b2be1db'
            ELSE NULL
 END
 FROM DUAL

此查询始终返回null,但显而易见的结果应该是第一种情况。我在oracle中缺少关于字符串比较的东西吗?

2 个答案:

答案 0 :(得分:9)

你正在检查一个空字符串的字符串,因此有问题;在Oracle中,您最好检查字符串is not null

SELECT CASE WHEN '7C54D3E133830A78E040A8C010014B7D' is not null
            THEN '7C54D3E133830A78E040A8C010014B7D'
            WHEN 'e84a4433966c4b8996ce34905acff63d' is not null
            THEN 'e84a4433966c4b8996ce34905acff63d'
            WHEN '7faa9126b1c6412fa58375ab2b2be1db' is not null
            THEN '7faa9126b1c6412fa58375ab2b2be1db'
            ELSE NULL
 END
 FROM DUAL 

关于Oracle处理空字符串和null的方式,here你会发现更多

一个例子:

select q'['' = '']'         , case when '' = ''            then 'YES' else 'NO' end from dual union all
select q'['' is null]'      , case when '' is null         then 'YES' else 'NO' end from dual union all 
select q'['' = null ]'      , case when '' = null          then 'YES' else 'NO' end from dual union all 
select q'[null = null]'     , case when null = null        then 'YES' else 'NO' end from dual union all 
select q'[null is null]'    , case when null is null       then 'YES' else 'NO' end from dual union all 
select q'['' != '']'        , case when '' != ''           then 'YES' else 'NO' end from dual union all
select q'['' is not null]'  , case when '' is not null     then 'YES' else 'NO' end from dual union all
select q'['' != null ]'     , case when '' != null         then 'YES' else 'NO' end from dual union all
select q'[null != null]'    , case when null != null       then 'YES' else 'NO' end from dual union all
select q'[null is not null]', case when null is not null   then 'YES' else 'NO' end from dual

给出:

'' = ''           NO
'' is null        YES
'' = null         NO
null = null       NO
null is null      YES
'' != ''          NO
'' is not null    NO
'' != null        NO
null != null      NO
null is not null  NO

总之,在谈到NULL时,唯一可以依赖的检查是:  IS [NOT] NULL

答案 1 :(得分:3)

嗯,这种行为的原因是Oracle 没有空字符串,但是null;这是

的原因
   select case when 'abc' != ''  
      ....

实际上是

   select case when 'abc' != null

由于anything != nullnulltruefalsenull布尔逻辑),所有when都不会返回trueelse已执行。 正确的语法是

   SELECT CASE WHEN '7C54D3E133830A78E040A8C010014B7D' IS NOT NULL
               THEN '7C54D3E133830A78E040A8C010014B7D'
               WHEN 'e84a4433966c4b8996ce34905acff63d' IS NOT NULL
               THEN 'e84a4433966c4b8996ce34905acff63d'
               WHEN '7faa9126b1c6412fa58375ab2b2be1db' IS NOT NULL
               THEN '7faa9126b1c6412fa58375ab2b2be1db'
               ELSE NULL
          END
     FROM DUAL