我有一个存储过程,它有两个参数:
@PublishedFrom SMALLDATETIME = NULL,
@PublishedDeadline SMALLDATETIME = NULL
我希望当PublishedDeadline
为null时,WHERE
条件应为:
WHERE (dbo.Vacancies.StartDate >= @PublishedFrom
OR @PublishedFrom IS NULL)
但如果PublishedDeadline
不为空,那么WHERE
子句应该像
WHERE v.startdate <= @PublishedDeadline
and @PublishedFrom <= v.EndDate
如何在SQL中应用条件where子句?
请建议
答案 0 :(得分:4)
以下内容对您有用:
WHERE (PublishedDeadline IS NULL
AND (
dbo.Vacancies.StartDate >= @PublishedFrom
OR @PublishedFrom IS NULL
) OR (
PublishedDeadline IS NOT NULL
AND v.startdate <= @PublishedDeadline
AND @PublishedFrom <= v.EndDate
)
只需将IS NULL
/ IS NOT NULL
条件与其他条件结合起来
答案 1 :(得分:0)
由于您使用的是存储过程,因此您可能希望获得更详细,更易读的查询
if (@PublishedDeadline is NULL)
BEGIN
Select * from dbo.Vacancies
WHERE (dbo.Vacancies.StartDate >= @PublishedFrom
OR @PublishedFrom IS NULL)
END
else
BEGIN
Select * from dbo.Vacancies
WHERE v.startdate <= @PublishedDeadline
and @PublishedFrom <= v.EndDate
END