PL/SQL - Optional conditions in where-clause - without dynamic sql?

后端 未结 5 1798
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 13:51

I have a query where not all conditions are necessary. Here\'s an example of what it looks like when all conditions are used:

select num
from (select distinct q.         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-08 14:12

    The solution I've settled on is one that generates an dynamic SQL query that may look like this:

    select num
    from (select distinct q.NUM
           from cqqv q 
           where  (q.bcode = :bcode) 
                      and  (1=1 or :lb is null) 
                      and  (1=1 or :type is null) 
                      and  (q.edate> :edate) 
                    order by dbms_random.value()) subq 
    where rownum <= :numrows
    

    (in this example, the bcode and edate conditions were NOT optional, but the lb and type were)

    I think this is (or is very similar to) what Michal Pravda was suggesting, and our DBA here prefers this solution over the context variable solution. Thanks for all that helped and offered advice!

    A link our DBA found which details this solution is here:

    Ask Tom: On Popularity and Natural Selection

提交回复
热议问题