Does BETWEEN with dates actually work in SQL SERVER 2008

后端 未结 8 902
旧时难觅i
旧时难觅i 2021-01-20 00:36

According to cdonner, in his answer here and on his blog.

He claims that BETWEEN with date yields inconsistent results

From his blog:

<
相关标签:
8条回答
  • 2021-01-20 01:10

    You are correct that his code is flawed due to string comparisons.

    However, if you're using a datetime type rather than the new date type it doesn't matter. The reason is that you don't typically want an inclusive search anyway, and so rather than code like this:

    SELECT * FROM [MyTable] WHERE MyDateColumn BETWEEN @StartDate AND @EndDate
    

    you'd normally write it like this:

    SELECT * FROM [MyTable] WHERE MyDateColumn >= @StartDate AND MyDateColumn < @EndDate
    

    where @EndDate is actually one greater than the day you really want.

    I expect the problem is fixed for the new Date type, but I don't have SQL Server 2008 handy so I can't test it.

    0 讨论(0)
  • 2021-01-20 01:13

    Very useful discussion!

    I had similar issues, resolved by using CAST and CONVERT, as in:

    cast(CONVERT(varchar(8), [PostDate], 112)AS DATE) BETWEEN '2013-01-01' AND '2013-01-31'

    Works like a charm, as verified with multiple detailed validations.

    The "Cast(" is required (believe me, I have the bald spots to prove it). But didn't have to declare variables, etc.

    Would be interested in feedback, if I'm missing the boat with the method or my response.

    Thanks!

    0 讨论(0)
提交回复
热议问题