Arithmetic overflow error: Msg 8115, Level 16, State 2

Arithmetic overflow error: Msg 8115, Level 16, State 2

我遇到了一个存储过程问题,导致:

Arithmetic overflow error converting expression to data type int.

有两个 table,第一个从 ODBC 连接中提取数据。数据包含活动及其开始时间。有一个每天运行的存储过程将这些开始时间转换为 intervals.This 大部分时间都可以工作,但在去年大约有十几天由于算术溢出错误而失败。我试图将数据类型从 INT 更改为 Numeric,但这并没有解决问题。非常感谢任何help/thoughts/ideas!

存储过程:

insert into [DB].[dbo].[Final_Table]
([resourceName]
      ,[eventdatetime]
      ,[EV2]
      ,[IntervalTime]
      ,[event])

(
SELECT DS1.[resourceName]
      ,DS2.[eventdatetime]
      ,DS1.[eventdatetime] as EV2
      ,CONVERT(varchar(8), DATEADD(ms, DATEDIFF(SECOND, DS2.[eventdatetime], DS1.[eventdatetime]) * 1000, 0), 114) AS [IntervalTime]
      ,DS2.[event]
FROM [DB].[dbo].[Staging_Table] DS1

INNER JOIN [DB].[dbo].[Staging_Table] DS2
    ON DS1.[resourceName] = DS2.[resourceName]
    AND DS1.[ID] = DS2.[ID] + 1)

分期table:

CREATE TABLE [dbo].[Staging_Table](
    [ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [resourceName] [varchar](50) NULL,
    [eventdatetime] [datetime] NULL,
    [event] [varchar](9) NULL,
PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

分段中的数据table:

决赛table:

CREATE TABLE [dbo].[Final_Table](
    [resourceName] [varchar](50) NULL,
    [eventdatetime] [datetime] NULL,
    [EV2] [datetime] NULL,
    [IntervalTime] [varchar](8) NULL,
    [event] [varchar](9) NULL
) ON [PRIMARY]
GO

最终Table数据:

DATEDIFF 函数 return 和 INT。然后你将它乘以 1000 以获得以毫秒为单位的秒数的结果。

但是,有时这可能会导致 overflow。例如:

DECLARE @A DATETIME2 = '2000-01-01'
       ,@B DATETIME2 = '2001-01-01'


SELECT DATEDIFF(SECOND, @A, @B) * 1000

Msg 8115, Level 16, State 2, Line 5 Arithmetic overflow error converting expression to data type int.

所以,首先转换为 BIGINT

DECLARE @A DATETIME2 = '2000-01-01'
       ,@B DATETIME2 = '2001-01-01'


SELECT CAST(DATEDIFF(SECOND, @A, @B) AS BIGINT) * 1000

其实上面的方法并不能解决你的问题,因为如果你检查DATEADD函数:

The number argument cannot exceed the range of int. In the following statements, the argument for number exceeds the range of int by 1. These statements both return the following error message: "Msg 8115, Level 16, State 2, Line 1. Arithmetic overflow error converting expression to data type int."

这意味着即使您将 BIGINT 值传递给它(在转换之后),您仍将继续收到此错误:

DECLARE @C BIGINT = 31622400000    
SELECT DATEADD(MILLISECOND,  @C  , 0)

您需要以不同的方式处理这种情况。例如,如果您的差异超过 INT.

,则设置 MAX
DECLARE @A DATETIME2 = '2000-01-01'
       ,@B DATETIME2 = '2001-01-01'

SELECT TRY_CAST(CAST(DATEDIFF(SECOND, @A, @B) AS BIGINT) * 1000 AS INT)