开发者

The result of [Datetime + 420./1440] (7 hours) is wrong (precision in ms is lost)

Could pls explain why I' not able to get valid result ( with precision to miliseconds ) after doing this (adding 7hrs to date):

select getdate() as dt into #t1
select dt, dt+(7.*6开发者_开发技巧0/1440) as dt_new from #t1

I got:

dt                      dt_new
2010-10-25 04:56:33.640 2010-10-25 11:56:33.580

As you can see there is difference in 60ms for dt_new - WHY? AFAIR I WAS able to do this sort of things in Oracle 10g - even with minutes: date + 5/1440 -to produce 5-min periods of datetime.

UPD:

My mistake - the CORRECT way of doing this is:

select getdate(), getdate()+(convert(float, 5)/1440) as dt_new 

I suppose there is wrong implicit convertion choosen by Ms Sql server.

UPD2: Thanks for replies, but my point was "arifmetic" method - because there are cases when calculating dates without dateadd really improves Query Plan - by eliminating Table scan that is the case with Dateadd and other functions. Anyway it works - thanks!


You could also use the inbuilt functions, such as

select dt, DATEADD(hour, 7, dt) as dt_new from #t1

My guess as to the imprecision in using + is that its converting from datetime to integer, then back again.


Actually, the even correcter way of adding 7 hours to a datetime is to use DATEADD:

select getdate() as dt into #t1
select dt, dateadd(hh, 7, dt) as dt_new from #t1

gives

dt                      dt_new
----------------------- -----------------------
2010-10-25 13:16:35.067 2010-10-25 20:16:35.067


You could achieve better result with dateadd() function (like previous posters noted). If you want use arithmetics, use better datatype, like float - cast(7 as float) instead of 7. is working well.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜