首页 > 解决方案 > 如何根据输入参数在 select 查询的 where 子句中运行特定条件?

问题描述

我正在尝试根据输入的参数使 NVL 工作的条件,但它不适用于 CASE 语句。当我的类型参数输入为“小时”时,我无法运行NVL(hours,0)>0条件 ,反之亦然

SELECT * 
FROM   hours_tbl 
WHERE  1=1 
AND 
       CASE 
              WHEN :type ='Hours' THEN Nvl(hours,0)>0 
              WHEN :type ='Earnings' THEN Nvl(hours,0)=0 
              ELSE Nvl(hours,0)>=0

标签: sqloracleoracle11gcasewhere-clause

解决方案


CASE不符合您的预期。它旨在分配值,而不是生成条件。我认为你想要 OR

select * 
from hours_tbl 
where 
    1=1
    and (
        ( :type ='Hours' and nvl(hours, 0) > 0 )
        or ( :type ='Earnings' and nvl(hours, 0) =0 )
        or ( :type not in ('Hours','Earnings') and nvl(hours, 0) >= 0 )
    )

注意:正如@TonyAndrew所言,如果:type可能NULL的话,最后一个表达式应该写成:

( nvl(:type,'x') not in ('Hours','Earnings') and nvl(hours, 0) >= 0 )

推荐阅读