SQL Server date comparisons based on month and year only

后端 未结 6 962
南方客
南方客 2021-02-05 06:27

I am having trouble determining the best way to compare dates in SQL based on month and year only.

We do calculations based on dates and since billing occurs on a monthl

6条回答
  •  灰色年华
    2021-02-05 07:18

    First, I'd use a format for the dates that is unambiguous, like the standard 'YYYYMMDD' and not the '6/15/2014' you have been using. Aaron Bertrand's blog explains far better than I could, the various ways this can go wrong:
    Bad habits to kick : mis-handling date / range queries

    For the specific problem, your last query which finds the first and the last days of the months (for date1 and date3), is in my opinion on the right track. You only need though the first days of months (first day of date1 and first day of next month for date3), if you avoid the evil BETWEEN: What do BETWEEN and the devil have in common?

    SELECT * 
    FROM tableName 
    WHERE date2 >= DATEADD(month, DATEDIFF(month, '19000101', @date1), '19000101')
      AND date2 < DATEADD(month, 1+DATEDIFF(month, '19000101', @date3), '19000101') ;
    

    The query works as it is, no matter the datatype of date2 (DATE, DATETIME, DATETIME2 or SMALLDATTEIME).

    Bonus point, indexes on date2 will be considered by the optimizer this way.


    Improvement, according to (yet, another) Aaron's blog post, to avoid a problem with cardinality estimation when evaluating expressions with DATEDIFF():
    Performance Surprises and Assumptions : DATEDIFF

    SELECT * 
    FROM tableName 
    WHERE date2 >= CONVERT(DATE, DATEADD(day, 1 - DAY(@date1), @date1))
      AND date2 < DATEADD(month, 1, 
                          CONVERT(DATE, DATEADD(day, 1 - DAY(@date3), @date3))) ;
    

提交回复
热议问题