使用提示执行where子句中的所有条件

时间:2016-12-21 06:15:05

标签: sql oracle optimizer-hints

考虑如下查询:

select * from <table_name>
where <condition1> and <condition2> and <condition3>;

假设Oracle执行条件(任何条件),如果不是,则不执行其他条件。因此,如果我有其他条件有逻辑错误,那么它不会被抛出。例如:

select count(*) from dual 
where 1=0 and 
'stack' = SUBSTR('stackoverflow','k', 3);

Oracle返回0.现在删除1 = 0条件,我们得到ORA-01722: invalid number

我知道Oracle会进行成本优化并决定条件执行的顺序。那么如何覆盖它并使其执行所有条件以便抛出错误而不是误导性输出?我们可以使用提示吗?我是提示概念的新手,所以一些例子会很棒。

4 个答案:

答案 0 :(得分:1)

我不知道这是否能解决你的问题&#34;不管它是什么,但这是一种方法。此查询或多或少与您的查询等效,并引发错误。

SQL> with t as (
  2  select /*+ materialize */ * from   dual
  3   where  'stack' = substr('stackoverflow', 'k', 3)
  4  )
  5  select * from t where 1 = 0;
 where  'stack' = substr('stackoverflow', 'k', 3)
                                          *
ERROR at line 3:
ORA-01722: invalid number

但不保证。 materialize只是一个提示,因此可能无法遵守。

答案 1 :(得分:0)

您可以逐个检查条件,或只使用OR关键字检查错误。

    select count(*) from dual 
    where 'stack' = SUBSTR('stackoverflow',1,5) and  1=0
   --  True and False return 0


    select count(*) from dual 
    where 'stack' = SUBSTR('stackoverflow','a',5) and  1=0
    --  True and False  return 0


   select count(*) from dual 
   where 'stack' = SUBSTR('stackoverflow',1,5) and  1=1
   --  True and True Return 1

这里oracle首先检查错误的条件1 = 0然后它不检查另一个条件,它也有逻辑错误,如无效数字&#39; a&#39;在substr语法中。

答案 2 :(得分:0)

  

XY问题是询问您尝试的解决方案而不是   你的实际问题。这导致大量的浪费时间和   能源,无论是寻求帮助的人还是部分人   提供帮助的人。

xyproblem.info

FYI

曾经有过ORDERED_PREDICATES提示
Optimizer Hints

在10g中被弃用了 What's New in Oracle Performance?

答案 3 :(得分:0)

select  *

from    <table_name>

where   case 
            when    <condition1> 
            then    case
                        when    <condition2> 
                        then    case
                                    when    <condition3>
                                    then    1
                                end
                    end
        end = 1