错误:将表达式转换为数据类型int的算术溢出错误

时间:2017-05-22 10:47:12

标签: sql sql-server

以下查询返回以下错误。

  

Msg 8115,Level 16,State 2,Line 1算术溢出错误   将表达式转换为数据类型int。警告:空值是   通过聚合或其他SET操作消除。

的Sql

SELECT
  Brands.BrandName AS [Brand],
  Outlets.OutletName AS [Outlet],
  AVG(DATEDIFF(ms, Orders.OrderDate, ReceivedOrders.ReceivingDate)) / 60000 AS [Receive],
  AVG(DATEDIFF(ms, ReceivedOrders.ReceivingDate, ReadyOrders.ReadyDate)) / 60000 AS [Ready],
  AVG(DATEDIFF(ms, ReadyOrders.ReadyDate, DispatchedOrders.DispatchedDate)) / 60000 AS [Dispatch],
  AVG(DATEDIFF(ms, DispatchedOrders.DispatchedDate, ClosedOrders.ClosingDate)) / 60000 AS [Close]
FROM dbo.Orders
INNER JOIN dbo.Outlets
  ON dbo.Orders.OutletID = dbo.Outlets.OutletID
INNER JOIN dbo.Brands
  ON dbo.Brands.BrandID = dbo.Outlets.BrandID
INNER JOIN dbo.ReceivedOrders
  ON dbo.Orders.OrderID = dbo.ReceivedOrders.OrderID
LEFT JOIN dbo.ReadyOrders
  ON dbo.Orders.OrderID = dbo.ReadyOrders.OrderID
LEFT JOIN dbo.DispatchedOrders
  ON dbo.Orders.OrderID = dbo.DispatchedOrders.OrderID
LEFT JOIN dbo.ClosedOrders
  ON dbo.Orders.OrderID = dbo.ClosedOrders.OrderID
WHERE Orders.OrderDate BETWEEN '2017-04-1' AND '2017-05-10'
AND ((dbo.Brands.BrandName IS NULL
OR dbo.Brands.BrandName LIKE '%' + '' + '%')
AND (dbo.Outlets.OutletName IS NULL
OR dbo.Outlets.OutletName LIKE '%' + '' + '%'))
GROUP BY Brands.BrandName,
         dbo.Outlets.OutletName
ORDER BY dbo.Outlets.OutletName, Brands.BrandName

2 个答案:

答案 0 :(得分:1)

你的日期之间有很多毫秒 - 然后你划分 - 这意味着SQL需要进行转换 - 显然,你已经溢出了它试图转换o的整数类型的日期。

所以,你得到的日期之间的差异为毫秒,然后除以60,000得到分钟。为什么不在几分钟内开始使用?这种溢出的可能性要低得多。

而不是:

AVG(DATEDIFF(ms, Orders.OrderDate, ReceivedOrders.ReceivingDate)) / 60000 AS [Receive]

执行:

AVG(DATEDIFF(mi, Orders.OrderDate, ReceivedOrders.ReceivingDate)) AS [Receive]

答案 1 :(得分:0)

我认为毫秒最大差值为25天左右:所以你可以改为秒并相应地划分

  AVG(DATEDIFF(s, Orders.OrderDate, ReceivedOrders.ReceivingDate)/60.0) AS [Receive],
  AVG(DATEDIFF(s, ReceivedOrders.ReceivingDate, ReadyOrders.ReadyDate)/60.0)  AS [Ready],
  AVG(DATEDIFF(s, ReadyOrders.ReadyDate, DispatchedOrders.DispatchedDate)/60.0)  AS [Dispatch],
  AVG(DATEDIFF(s, DispatchedOrders.DispatchedDate, ClosedOrders.ClosingDate)/60.0) AS [Close]

MSDN: 如果返回值超出int(-2,147,483,648到+2,147,483,647)的范围,则返回错误。毫秒,startdate和enddate之间的最大差异是24天,20小时,31分钟和23.647秒。

https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql