带有in值的where子句中的case语句oracle sql

时间:2018-06-20 17:50:29

标签: sql oracle select case oracle-apex

我正在研究Oracle Apex应用程序。我有一个简单的select查询,它工作正常,但现在我想在该查询中执行if / else或case语句。

所以查询在下面

select value d,
       id r
  from dhm_lov_data
 where lov_id = 103
   and nvl(isdeleted,0) = 0
   and parentid_1 =:p21_typeid
 order by d

我想更改此查询以在:P21_TYPEID值上添加条件。 例如。如果:P21_TYPEID的值为1,则在where子句中,其值为PARENTID_1 in (10,11) 否则为PARENTID_1 = :P21_TYPEID

我试图将其放在case语句中,但是没有用。下面是查询,我正在尝试使用case语句

SELECT  VALUE d, id r FROM DHM_LOV_DATA WHERE LOV_ID= 103 and nvl(ISDELETED,0) = 0  
and 
case when :P21_TYPEID = 848 then PARENTID_1 in (287,288)
    else PARENTID_1 = :P21_TYPEID  end;
order by d

2 个答案:

答案 0 :(得分:3)

case表达式返回一个值,而不是您可以添加到where子句中的条件。但是您可以使用一些布尔运算符来模拟这种行为:

SELECT   value d, id r 
FROM     dhm_lov_data
WHERE    lov_id = 103 AND
         NVL(isselected, 0) = 0 AND
         (:P21_TYPEID = 848 AND parentid_1 IN (287,288) OR
          :P21_TYPEID = parentid_1)
ORDER BY d

答案 1 :(得分:0)

也许像这样的 ugly 例子?

select  value d, id r 
from dhm_lov_data 
where lov_id = 103 
  and nvl(isdeleted, 0) = 0  
  and parentid_1 in (select :p21_typeid from dual
                     where :p21_typeid <> 848
                     union
                     select val from (select 287 val from dual 
                                      union
                                      select 288 val from dual
                                     )
                     where :p21_typeid = 848
                    )