Using WHERE clause with BETWEEN and null date parameters

前端 未结 6 809

One of my WHERE clauses is the following:

AND (DateCreated BETWEEN @DateFrom and @DateTo OR (@DateFrom IS NULL OR @DateTo IS NULL))
6条回答
  •  一个人的身影
    2021-01-04 01:19

    Just need some extra criteria to handle when one or the other is NULL:

    AND (
        (DateCreated >= @DateFrom and DateCreated < DATEADD(day,1,@DateTo)) 
     OR (@DateFrom IS NULL AND @DateTo IS NULL)
     OR (@DateFrom IS NULL AND DateCreated < DATEADD(day,1,@DateTo))
     OR (@DateTo IS NULL AND DateCreated >= @DateFrom)
        )
    

    Edit: Giorgi's approach was simpler, here it is adapted for use with DATETIME:

    AND (       (DateCreated >= @DateFrom OR @DateFrom IS NULL) 
            AND (DateCreated < DATEADD(day,1,@DateTo) OR @DateTo IS NULL)
        )
    

    The issue with BETWEEN or <= when using a DATE variable against a DATETIME field, is that any time after midnight on the last day will be excluded.

    '2015-02-11 13:07:56.017' is greater than '2015-02-11' Rather than casting your field as DATE for comparison, it's better for performance to add a day to your variable and change from <= to <.

提交回复
热议问题