Using WHERE clause with BETWEEN and null date parameters

前端 未结 6 765

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:13

    This can simply be done by using ISNULL function.

    DateCreated BETWEEN ISNULL(@DateFrom,DateCreated) AND ISNULL(@DateTo,DateCreated)
    
    0 讨论(0)
  • 2021-01-04 01:14

    Try this:

    WHERE ((DateCreated >= @DateFrom OR @DateFrom IS NULL) AND (DateCreated =< @DateTo OR @DateTo IS NULL))
    
    0 讨论(0)
  • 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 <.

    0 讨论(0)
  • 2021-01-04 01:20

    How About:

    DateCreated BETWEEN COALESCE(@DateFrom, DateCreated) AND COALESCE(@DateTo, DateCreated)
    
    0 讨论(0)
  • 2021-01-04 01:21

    Use this where clause

    WHERE  ( DateCreated BETWEEN @DateFrom AND @DateTo )
            OR ( @DateFrom IS NULL
                 AND @DateTo IS NULL )
            OR ( @DateFrom IS NULL
                 AND DateCreated <= @DateTo )
            OR ( @DateTo IS NULL
                 AND DateCreated >= @DateFrom ) 
    
    0 讨论(0)
  • 2021-01-04 01:22
    AND (DateCreated BETWEEN @DateFrom and @DateTo OR (ISNULL(@DateFrom, '')='' OR ISNULL(@DateTo, '')=''))
    
    0 讨论(0)
提交回复
热议问题