sql - 如何根据输入参数在 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
解决方案
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 )
推荐阅读
- android - 需要从网站访问 Chrome 密钥库
- angular - 如何在我的 Spring boot Angular 应用程序中配置打印机,或者如何在 Spring-boot Angular 应用程序中实现打印机?
- python - 如何基于节点之间的其他边有条件地在网络中创建边(使用 python Networkx 包)?
- javascript - TS | 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“记录”
' - office365 - O365 Outlook 插件:在商店发布时的验证问题 [4.18]
- plasticscm - PlasticSCM 升级 - Client.conf 根元素丢失
- dialogflow-es - 测试实体条目的有效性
- events - Esper 没有保护对象并导致聚合对象 oom
- android - 在android中单击一个按钮而不是它的操作按钮时关闭一个快餐栏
- java - 如何从 Mockito 类中为不返回值的 Save 方法调用/生成异常?