2017-09-25 126 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)