T-SQL Between Dates Confusion

后端 未结 5 491
一生所求
一生所求 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:19

    A date is a point in time, not a time span.

    '12/31/2010' is a point, too. Namely, it's the midnight of the 31st of December.
    Everything that happened after this point is ignored.
    That's exactly the behaviour you want (even if you haven't realised that yet).

    Do not think that when you choose to omit the time part, it is magically assumed to be "any". It's going to be "all zeroes", that is, the midnight.

    If you want to include the entire day in your query without having to specify 23:59:59 (which, by the way, excludes the last second of the day, between the moment 23:59:59 of the current day and the moment 00:00:00 of the next day), you can do that either by using strict inequalities (>, <) bounded by the first points of time you don't want:

    WHERE TRANDATE >='12/01/2010 00:00:00' and TRANDATE < '01/01/2011'
    

    or by comparing date values casted to DATE:

    WHERE CAST(TRANDATE AS DATE) between '12/01/2010' and '12/31/2010'
    

    (it is okay to put this type of cast in a WHERE clause, it is sargable).

提交回复
热议问题