Does BETWEEN with dates actually work in SQL SERVER 2008

后端 未结 8 912
旧时难觅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 00:59

    SQL server stores datetime values as a number. For instance, 0 is 1900-01-01 00:00:00.000

    The example you give in your question is subject to rounding problems, similar to how the floating-point value 1.0 is stored as 0.99999...

    To accurately compare dates, you would cast the value to a datetime type and then do your comparison.

    SELECT
    CASE 
        WHEN cast('1/1/08' as datetime) 
            BETWEEN cast('1/1/08' as datetime) AND cast('2/1/08' as datetime) 
        THEN 'in' ELSE 'out' 
    END AS s1,
    CASE 
        WHEN cast('1/1/08' as datetime) 
            BETWEEN cast('12/31/07' as datetime) AND cast('1/1/08' as datetime) 
        THEN 'in' ELSE 'out' 
    END AS s2
    

    Which will result in your expected output: s1==in, s2==in

提交回复
热议问题