[英]Elegant way to filter a record with nullable field in SQL using nullable parameter
[英]Filter nullable column for nullable parameter SQL
我在表中有一个StartDate
& EndDate
列,它们可以为空,我将向存储过程传递两个参数以过滤该表,这些参数可以为空值,并且这些列也可以为空。
在这种情况下,如何编写带有条件WHERE
子句的SQL语句以获取大于或等于StartDate
的日期和小于或等于EndDate
的日期?
到目前为止,这是我所做的:
SELECT StartDate, EndDate FROM Table1
WHERE (StartDate >= Convert(DateTime, @dtFrom) OR StartDate IS NOT NULL ) AND
(EndDate <= Convert(DateTime, @dtTo) OR EndDate IS NOT NULL )
如果空参数表示“不对该参数进行过滤”,而列中的空值表示正/负无穷大,则可能要使用以下查询:
select StartDate, EndDate
from Table1
where
(@dtFrom is null or StartDate is null or StartDate >= Convert(DateTime, @dtFrom)) and
(@dtTo is null or EndDate is null or EndDate <= Convert(DateTime, @dtTo))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.