简体   繁体   English

SQL Server 2008 BETWEEN函数

[英]SQL Server 2008 BETWEEN function

Here is my code: 这是我的代码:

DECLARE @d1 DATETIME
DECLARE @d2 DATETIME

SET @d1 = '2015-01-01 00:00:00'
SET @d2 = '2015-12-31 23:59:59.999'

SELECT 
    CASE 
       WHEN ('2016-01-01 00:00:00' BETWEEN @d1 AND @d2) 
          THEN 'is between' 
          ELSE 'not between'
    END  AS BetweenOrNotBetween

The date I supplied here is 1 msec later than the range of the BETWEEN function, yet on my SQL 2008 server instance, the result is 'is between' and not the expected 'not between' ... 我在此处提供的日期比BETWEEN函数的范围 1毫秒, 在我的SQL 2008 Server实例上,结果是“在...之间”而不是预期的“不在 ... 之间” ...

Is this a bug, or is it a necessary compromise in the design for some reason I'm not seeing? 这是一个错误,还是由于我看不见的某种原因而在设计中进行了必要的折衷?

And yes, as soon as I add even a fraction of a second beyond midnight of 2016-01-01, I get the expected 'not between' result. 是的,只要我在2016年1月1日午夜之后添加了不到一秒的时间,我就会得到预期的“不在中间”结果。

Look at documentation for datetime type . 查看日期时间类型的文档。 In section Rounding of datetime Fractional Second Precision you will find the explanation to your issue: Rounding of datetime Fractional Second Precision部分中Rounding of datetime Fractional Second Precision您会找到有关问题的说明:

datetime values are rounded to increments of .000, .003, or .007 seconds, as shown in the following table. 下表将datetime值四舍五入为.000,.003或.007秒。

This means that if you have 1 millisecond, it is actually rounded to 0 milliseconds, so your result is is between . 这意味着如果您有1毫秒,则实际上将其舍入为0毫秒,因此您的结果is between Unfortunatelly this is how datetime data type works, there is not much you can do about this, unless you can use other data type, like datetime2 . 不幸的是,这是datetime数据类型的工作方式,对此您无能为力,除非您可以使用其他数据类型,例如datetime2

If you use the code below, you'll see that the problem is the datetime type. 如果使用下面的代码,则会发现问题出在日期时间类型上。 Look at the documentation about datetime and your doubt will be solved! 查看有关日期时间的文档,您的疑问将得到解决!

DECLARE @d1 datetime2
DECLARE @d2 datetime2

SET @d1 = '2015-01-01 00:00:00.00'
SET @d2 = '2015-12-31 23:59:59.999'

SELECT CASE WHEN ('2016-01-01 00:00:00.00' BETWEEN @d1 AND @d2 ) THEN 'is between' 
       ELSE 'not between'
       END  AS BetweenOrNotBetween

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM