当列值为 null 时,不要在 where 条件中追加"and"子句



我有一个查询,其中我不想在列值为空时在 where 条件中附加"and"子句,例如

select * from x where x.abc = 'ACTIVE' and x.start_date < sysdate and x.end_date > sysdate

所以在这种情况下x.end_date我希望它仅在其值不为空时才适用。没有任何存储过程,只是一个简单的查询。

我还想使用条件生成器和谓词将此查询转换为 spring-data jpa 规范。

您可以使用or

select *
from x
where x.abc = 'ACTIVE' and
x.start_date < sysdate and
( x.end_date > sysdate or x.end_date is null );

你可以看看NVL函数。

select * from x
where x.abc = 'ACTIVE' 
and x.start_date < sysdate 
and NVL(x.end_date,sysdate) >= sysdate

并不是说其他答案不正确或不好,但我会写得有点不同,我把它贴在这里,希望有人对为什么一种方式可能比另一种方式更好有一个有趣的评论。

这是我要写的:

select * from x
where x.abc = 'ACTIVE' 
and sysdate between x.start_date and nvl(x.end_date,sysdate);

对我来说,即:"当前日期必须在记录的有效日期范围内"。

最新更新