将expression转化为数据类型int时发生算术溢出错误

在SQL Server 中,某列的数据都在int范围之内,但是使用sum聚集函数求该列和的时候,出现“将expression转化为数据类型int时发生算术溢出错误”。

问题在于定义的数据类型:

首先,我们先看看SQL Server 定义的数据类型的长度:

  • bigint   数据类型存储从   -2^63   (-9223372036854775808)   到   2^63-1   (9223372036854775807)   范围内的数字。存储大小为   8   个字节。   
  •      int   数据类型的存储范围是   -2,147,483,648   至   2,147,483,647(每个值需   4   个字节的存储空间)。   
  •      smallint   数据类型的存储范围只有   -32,768   至   32,767(每个值需   2   个字节的存储空间),tinyint   数据类型只能存储   0   至   255   范围内的数字(每个值需   1   个字节的存储空间)。

当我们对int类型的数据做sum操作的时候,就有可能发生算术溢出的问题。此时,我们可以采用在做sum操作前,将原有列的数据类型更改为bigint 。

SQL 语句: 

1. select   sum(cast(colName   as   bigint))   from   TableName

2. select   sum(convert(numeric(20,0),colName))   from   TableName

以上两种方法都是可以的。

在SQL Server 2005 中,我进行了测试:

[xhtml]  view plain  copy
 
  1. declare @a int   
  2.     , @b int   
  3.     , @c bigint  
  4. set @a = 1000000000  
  5. set @b = 2000000000  
  6. --1.  
  7. set @c = @a + @b  
  8. --2.  
  9. --set @c = cast( @a as bigint)  + cast( @b as bigint)  
  10. --3.  
  11. --set @c = convert(numeric(20,0),@a) + convert(numeric(20,0),@b)  
  12. select @c  

使用方法1,虽然定义@c为bigint 类型,但是 仍然会出现“Arithmetic overflow error converting expression to data type int.” 错误。

通过方法2 和方法3 ,均可以得到最后结果为 3000000000

转自:https://blog.csdn.net/spring21st/article/details/5345338

猜你喜欢

转载自www.cnblogs.com/gered/p/9131966.html