SQL query to select dates between two dates

后端 未结 22 1677
囚心锁ツ
囚心锁ツ 2020-11-22 09:10

I have a start_date and end_date. I want to get the list of dates in between these two dates. Can anyone help me pointing the mistake in my query.<

22条回答
  •  余生分开走
    2020-11-22 09:51

    This is very old, but given a lot of experiences I have had with dates, you might want to consider this: People use different regional settings, as such, some people (and some databases/computers, depending on regional settings) may read this date 11/12/2016 as 11th Dec 2016 or Nov 12, 2016. Even more, 16/11/12 supplied to MySQL database will be internally converted to 12 Nov 2016, while Access database running on a UK regional setting computer will interpret and store it as 16th Nov 2012.

    Therefore, I made it my policy to be explicit whenever I am going to interact with dates and databases. So I always supply my queries and programming codes as follows:

    SELECT FirstName FROM Students WHERE DoB >= '11 Dec 2016';
    

    Note also that Access will accept the #, thus:

    SELECT FirstName FROM Students WHERE DoB >= #11 Dec 2016#;
    

    but MS SQL server will not, so I always use " ' " as above, which both databases accept.

    And when getting that date from a variable in code, I always convert the result to string as follows:

    "SELECT FirstName FROM Students WHERE DoB >= " & myDate.ToString("d MMM yyyy")
    

    I am writing this because I know sometimes some programmers may not be keen enough to detect the inherent conversion. There will be no error for dates < 13, just different results!

    As for the question asked, add one day to the last date and make the comparison as follows:

    dated >= '11 Nov 2016' AND dated < '15 Nov 2016' 
    

提交回复
热议问题