Sql条件语句在where子句中

时间:2012-01-16 20:24:20

标签: sql sql-server sql-server-2008

我想使用条件进行查询以选择过滤器的子句。 这样的事情。

SELECT Id,name,last_name,submitDate,lastvisitDate 
from Visitor Where if(submitDate is not null) begin submitDate >= @dateFrom end
and if(submitDate is not null) begin submitDate < @dateTo end

但我需要举例说明@dateTo is null此变量不参与过滤查询

4 个答案:

答案 0 :(得分:2)

where (submitDate is null or (submitDate >= @dateFrom and submitDate < @dateTo))

答案 1 :(得分:1)

select * from Visitor where (submitDate is null or submitDate >= @dateFrom) and (submitDate is null or submitDate < @dateTo)

答案 2 :(得分:1)

您可以将ISNULL应用于@dateTo,从而将其默认为某个非常遥远的未来日期,例如30000101

…
WHERE submitDate IS NULL
   OR submitDate >= @dateFrom AND submitDate < ISNULL(@dateTo, '30000101')

答案 3 :(得分:0)

我已更新示例查询的WHERE子句,因此如果submitDate为null或者submitDate介于@dateFrom和@dateTo之间,则记录将包含在结果中

SELECT Id, name, last_name, submitDate, lastvisitDate 
FROM Visitor 
WHERE (submitDate IS NULL) OR ((submitDate >= @dateFrom) AND (submitDate < @dateTo))