2017-09-25 124 views
0

我試圖做一個查詢,當定義句點的兩個週期參數爲空時,給出所有記錄,並且只選擇當參數不爲空時我需要的記錄。SQL - 如果2日期參數爲空顯示全部

的兩個參數是@PeriodFrom@PeriodeUntil 我試圖做類似

SELECT DISTINCT Field 
FROM Table 
WHERE StartDate BETWEEN 
    CASE WHEN @PeriodeFrom IS NULL AND @PeriodeTot IS NULL 
    THEN StartDatum AND CAST(GETDATE() AS Date) 
    ELSE @PeriodeVan 
    AND @PeriodeTot 

這一個不工作。

回答

0

您可以用簡單的布爾邏輯

SELECT DISTINCT Field 
FROM Table 
WHERE (@PeriodFrom IS NULL AND @PeriodUntil IS NULL) 
OR (StartDate BETWEEN @PeriodFrom AND @PeriodUntil) 
+1

我想知道是否可以,要麼@ PeriodFrom或@ PeriodUntil可以爲空 –

+0

看到我的欺騙投票建議:https://stackoverflow.com/questions/ 28459783/using-where-clause-with-between-and-null-date-parameters – Tanner

+0

@DmitrijKultasev當然,將'AND'改爲'OR' – Jamiec

0

第一處理空值的參數,那麼範圍內做到這一點。

… 
where (@PeriodeFrom is null and @PeriodeUntil is null) 
    or StartDatum between @PeriodeFrom and @PeriodeUntil 
0

使用ISNULL:

SELECT DISTINCT Field 
FROM [Table] 
WHERE StartDate BETWEEN isnull(@PeriodeFrom, StartDate) AND isnull(@PeriodeTot, Startdate)