SQL Server : fetching records between two dates?

前端 未结 6 911
暖寄归人
暖寄归人 2020-12-13 21:23

In SQL I write a SELECT statement to fetch data between two dates, using between and

Ex:

select * 
from xxx 
where dates b         


        
6条回答
  •  [愿得一人]
    2020-12-13 22:04

    Your question didnt ask how to use BETWEEN correctly, rather asked for help with the unexpectedly truncated results...

    As mentioned/hinting at in the other answers, the problem is that you have time segments in addition to the dates.

    In my experience, using date diff is worth the extra wear/tear on the keyboard. It allows you to express exactly what you want, and you are covered.

    select * 
    from xxx 
    where datediff(d, '2012-10-26', dates) >=0
    and  datediff(d, dates,'2012-10-27') >=0
    

    using datediff, if the first date is before the second date, you get a positive number. There are several ways to write the above, for instance always having the field first, then the constant. Just flipping the operator. Its a matter of personal preference.

    you can be explicit about whether you want to be inclusive or exclusive of the endpoints by dropping one or both equal signs.

    BETWEEN will work in your case, because the endpoints are both assumed to be midnight (ie DATEs). If your endpoints were also DATETIME, using BETWEEN may require even more casting. In my mind DATEDIFF was put in our lives to insulate us from those issues.

提交回复
热议问题