2014-02-16 69 views
1

我有它有兩個參數的存儲過程:有條件的where子句中的SQL日期範圍

@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子句?

請建議

回答

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 
     ) 

只是與其他條件

+0

我是否需要添加檢查對於發佈後的第二部分是否爲空? – DotnetSparrow

+0

這取決於您希望查詢的行爲如何。沒有關於你的意圖的所有信息,我不能回答這個問題。但是,我可以說,像'NULL <= something'這樣的比較會給你'NULL'的結果。 – Alexander

+0

@DotnetSparrow如果您不確定,只需在'PublishedDeadline IS NOT NULL'之後添加'AND PublishedFrom IS NOT NULL' – Alexander

0

結合IS NULL/IS NOT NULL條件,因爲你是在存儲過程的工作,你可能希望有更詳細,更易讀的查詢

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