暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 在 “case when” 子句中使用1> 0时的错误

askTom 2018-02-20
947

问题描述

大家好!

最近,我在构建SQL查询时发现了一个奇特的情况。目的是使用 “case” 语句添加 “where” 子句,该语句旨在验证确定的条件是否大于零。为了更好地理解,我复制了一个 “with” 子句,所以在这里:

with test as (
   select 1 as col from dual
   union all
   select 2 as col from dual
)
select *
 from test
where (case when 1 = 1 then 1 else (select count(*) from dual where 1 = 0) end) > 0;
复制


该查询应该检索以下行:

col
----------
1
2
----------

正如我们所知道的,一个是等于一个,但是当我添加了从 “不可能检索条件” (零等于一) 的对偶计数的 “其他” 条件时,它似乎像Oracle停止进入第一个条件 (1 = 1) 并进入第二个条件,返回零线。

当我不在 “else” 语句处使用count(*) 时,返回结果,甚至认为count结果为零,与以下查询相同:

with test as (
   select 1 as col from dual
   union all
   select 2 as col from dual
)
select *
 from test
where (case when 1 = 1 then 1 else 0 end) > 0;
复制


另一个奇怪的事实: 如果我将 “> 0” 交换为 “> = 1”,则可以正常工作。

有什么线索吗?我还没有弄清楚是什么导致了这个不寻常的 “错误”。

谢谢。

专家解答

是的,这是一个描述的错误。我不知道哪个,但它是固定在12.1:

SQL> select * from v$version;

BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
PL/SQL Release 11.2.0.4.0 - Production
CORE    11.2.0.4.0      Production
TNS for Linux: Version 11.2.0.4.0 - Production
NLSRTL Version 11.2.0.4.0 - Production

SQL> with test as (
  2    select 1 as col from dual
  3    union all
  4    select 2 as col from dual
  5  )
  6  select *
  7   from test
  8  where (
  9    case
 10      when 1 = 1 then 1
 11      else (select count(*) from dual where 1 = 0)
 12    end
 13  ) > 0;

no rows selected

SQL> conn chris/chris@db121
Connected.
SQL> select * from v$version;

BANNER                                                                               CON_ID
-------------------------------------------------------------------------------- ----------
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production              0
PL/SQL Release 12.1.0.2.0 - Production                                                    0
CORE    12.1.0.2.0      Production                                                                0
TNS for Linux: Version 12.1.0.2.0 - Production                                            0
NLSRTL Version 12.1.0.2.0 - Production                                                    0

SQL> with test as (
  2    select 1 as col from dual
  3    union all
  4    select 2 as col from dual
  5  )
  6  select *
  7   from test
  8  where (
  9    case
 10      when 1 = 1 then 1
 11      else (select count(*) from dual where 1 = 0)
 12    end
 13  ) > 0;

       COL
----------
         1
         2
复制

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论