SQL Server: datediff function resulted in an overf

2019-03-24 16:34发布

I have the following query :

select CONVERT(varchar(12), DATEADD(MILLISECOND, DateDiff(MILLISECOND, '2014-08-04 10:37:28.713','2014-11-04 08:21:17.723'), 0), 114)

When I execute this, I get the error : "The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart."

When I change the query to the following it works fine :

select CONVERT(varchar(12), DATEADD(SECOND, DateDiff(SECOND, '2014-08-04 10:37:28.713','2014-11-04 08:21:17.723'), 0), 114)

The problem is that I really need the MILLISECONDS as well.

5条回答
唯我独甜
2楼-- · 2019-03-24 16:57

A bit later response but may help. In SQL 2016 MS introduced function DATEDIFF_BIG which will (according to type size) overflow in difference bigger than something like 290k years. But technet article have same time difference as basic DATEDIFF - https://msdn.microsoft.com/en-us/library/mt628058.aspx

查看更多
Rolldiameter
3楼-- · 2019-03-24 17:04

In SQL Server 2016 there is a new function available: DATEDIFF_BIG

It solves exactly the overflow problem.

查看更多
在下西门庆
4楼-- · 2019-03-24 17:13

For millisecond, the maximum difference between startdate and enddate is 24 days, 20 hours, 31 minutes and 23.647 seconds. see http://msdn.microsoft.com/en-us/library/ms189794.aspx

If you need millisecond above that level, you'll need to write something custom.

查看更多
你好瞎i
5楼-- · 2019-03-24 17:13

For me there was a big interval between two dates so i have used below code

declare @timetagInMillsecond bigint=CAST(CAST( cast(@timetag as datetime) -'1970-01-01' AS decimal(38,10))*24*60*60*1000+0.5 as bigint)

It works for me .

查看更多
一纸荒年 Trace。
6楼-- · 2019-03-24 17:20

You don't need to refer to the miliseconds in your calculation.

This will do exactly the same as your script except the overflow:

SELECT CONVERT(varchar(12), 
        CAST('2014-11-04 08:21:17.723' as datetime) - 
        CAST('2014-08-04 10:37:28.713' as datetime)
       , 114)
查看更多
登录 后发表回答