获得一个"为&datetime2'添加一个值?栏引起溢出"仅在大型数据集上运行时

时间:2017-02-06 20:46:35

标签: sql sql-server tsql

我基本上计算格式天数中两个日期之间的差异:小时:分钟:秒

CONVERT(varchar, datediff (s, [CreatedDate], [ClosedDate]) / (60 * 60 * 24)) + ':' + CONVERT(varchar, dateadd(s, datediff (s, [CreatedDate], [ClosedDate]), CONVERT(datetime2, '0001-01-01')), 108) AS Length

[CreatedDate],[ClosedDate]都在DATETIME2

如果我这样做:

SELECT top 10000然后按预期工作

但是当我执行SELECT *时,我收到此错误:

  

将值添加到' datetime2'列导致溢出。

我的方法不够理想吗?我需要改变什么?

感谢。

另外 - 这两个的最短日期是2015-07-01,所以我认为这不适用于此:http://www.devx.com/tips/Tip/13898

2 个答案:

答案 0 :(得分:1)

给它一个旋转,看看你是否有同样的错误......

select 
    convert(varchar(16),datediff(ss,[CreatedDate],[ClosedDate])/86400) + ':'+ 
    convert(varchar(16),(datediff(ss,[CreatedDate],[ClosedDate])/3600)%24) + ':'+ 
    convert(varchar(16),(datediff(ss,[CreatedDate],[ClosedDate])/60)%60) + ':'+ 
    convert(varchar(16),datediff(ss,[CreatedDate],[ClosedDate])%60)
where CreatedDate is not null and ClosedDate is not null

旁注,您没有收到SELECT TOP 1000中的错误,因为错误不在这些行中。我认为你在其中一列中有一个空白值...即空格而不是NULL值,这导致你的添加失败。

declare @d1 datetime2 = '1/1/2017'
declare @d2 datetime2 = ''

select @d1, @d2

select 
    dateadd(s, datediff (s, @d1, @d2),CONVERT(datetime2, '0001-01-01'))

答案 1 :(得分:1)

<Any>

返回

Declare @YourTable table ([CreatedDate] datetime2, [ClosedDate] datetime2)
Insert Into @YourTable values
('2015-07-01 12:30:00','2015-07-01 12:30:02'),  -- 2 sec
('2015-07-01 12:30:00','2015-07-01 12:35:02'),  -- 5 min 2 sec
('2015-07-01 12:30:00','2015-07-01 17:35:02'),  -- 5 hrs 5 min 2 sec
('2015-07-01 12:30:00','2015-07-02 12:30:00'),  -- exactly 1 day
('2015-07-01 12:30:00','2015-07-02 12:00:00'),  -- 30 min short of 1 day
('2015-07-01 12:30:00','2017-02-06 16:00:00'),   -- more than 1 year
('2015-07-01 12:30:00',null)                    -- Default to current datetime

Select *
      ,Elapsed = concat(DateDiff(SS,[CreatedDate],IsNull([ClosedDate],GetDate()))/86400,Format(DateAdd(S,DateDiff(SECOND,[CreatedDate],IsNull([ClosedDate],GetDate())),0),':HH:mm:ss'))
 From  @YourTable