Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 855
MonsterMMORPG Avatar asked Nov 27 '11 21:11

MonsterMMORPG


People also ask

What does arithmetic overflow error convert to data type int mean?

1. "Arithmetic overflow error converting IDENTITY to data type int" error means the value of IDENTITY is overflowing range of data type of that particular column.


2 Answers

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 
like image 54
Michał Powaga Avatar answered Sep 27 '22 23:09

Michał Powaga


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 )) 
like image 22
JayC Avatar answered Sep 28 '22 00:09

JayC