开发者

Strange datetime behavior in SQL Server

开发者 https://www.devze.com 2023-03-29 20:13 出处:网络
declare @data datetime set @data = \'2011-01-01 23:59:59:999\' select @data result is: 2011-01-02 00:00:00.000
 declare @data datetime
 set @data = '2011-01-01 23:59:59:999'
 select @data  
 

result is:

 2011-01-02 00:00:00.000

Second example:

 declare @data datetime
 set @data = '2011-01-01 23:59:59:999'
 select 1 where @data >= '2011-01-02 00:00开发者_开发问答:00:000'
 

result

 1

My question is why and how to make it correct?

edit

problem is in sql server 2008


You have a precision problem. .999 is rounded up to .000.

.997 is as close to the next day as you can get.

declare @data datetime
set @data = '2011-01-01T23:59:59.997'
select @data  

Have a look here at the section about "Rounding of datetime Fractional Second Precision" http://msdn.microsoft.com/en-us/library/ms187819.aspx

If you are on SQL Server 2008 you can use datetime2(3) if you want a precision down to the millisecond.


You need to use more precise format - datetime2 (YYYY-MM-DD HH:MM:SS:XXXXXXX)

 declare @data datetime2
 set @data = '2011-01-01 23:59:59:999'
 select 1 where @data >= '2011-01-02 00:00:00:000'
0

精彩评论

暂无评论...
验证码 换一张
取 消