T-SQL Between Dates Confusion

后端 未结 5 503
一生所求
一生所求 2020-12-03 18:22

I am working with T-SQL in SQL Server 2000 and I have a table TRANSACTIONS which has a date column TRANDATE defined as DateTime, among many other c

5条回答
  •  余生分开走
    2020-12-03 19:06

    As you have discovered, if you don't specify a time when entering a date, it defaults to midnight in the morning of the date. So 12/31/2010 stops at midnight when that day begins.

    To get all dates for 12/31/2010, you can either specify the time, as you have done, or add one day to the ending date. Without a time, 1/1/2011 ends at the stroke of midnight on 12/31/2010. So, you could do BETWEEN 12/1/2010 AND 1/1/2011. You can use DATEADD to add the day in your SQL if that makes it easier.

    There is some risk in that second approach of adding a day. You will get any records for 1/1/2011 that carry the time of 00:00:00.

    Here's one way to perform the DATEADD:

    DECLARE @FromDate datetime, @ToDate datetime
    // These might be stored procedure input parameters
    SET @FromDate = '12/1/2010'
    SET @ToDate = '12/31/2010'
    
    SET @ToDate = DATEADD(d, 1, @ToDate)
    

    Then you use @ToDate in your WHERE clause in the BETWEEN phrase in the usual way.

提交回复
热议问题