How to prevent arithmetic overflow error when using SUM on INT column?

倖福魔咒の 提交于 2019-12-18 12:09:25

问题


I am using SQL Server 2008 R2 and I have an INT column where the data inserted never surpasses the max INT, but I have a query which uses the SUM function which when executed surpasses the max INT limit and throws the error mentioned in the title.

I want to be able to execute this query without changing the column type from INT to BIGINT.

Here is my query:

SELECT    UserId,
          SUM( PokemonExp )     AS TotalExp,
          MAX( PokemonLevel )   AS MaxPokeLevel

FROM      mytable

GROUP BY  UserId
ORDER BY  TotalExp DESC

Note: The PokemonExp column is of type INT.


回答1:


Type of expression in SUM determines return type.

Try the following:

SELECT    UserId,
          SUM( CAST( PokemonExp AS BIGINT ))  AS TotalExp,
          MAX( PokemonLevel )                 AS MaxPokeLevel

FROM      mytable

GROUP BY  UserId
ORDER BY  TotalExp DESC



回答2:


You don't have to change the column type to BIGINT to get a proper sum.

Just CAST or CONVERT PokemonExp to BIGINT before you perform the SUM like follows:

SUM( CAST( PokemonExp AS BIGINT ))



回答3:


Accepted type of expression in SUM determines return type.

Try the following:

SELECT    UserId,
          SUM( CAST( PokemonExp AS BIGINT ))  AS TotalExp,
          MAX( PokemonLevel )                 AS MaxPokeLevel

FROM      mytable

GROUP BY  UserId
ORDER BY  TotalExp DESC


来源:https://stackoverflow.com/questions/8289310/how-to-prevent-arithmetic-overflow-error-when-using-sum-on-int-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!