1

Recently i was Playing with SQL Server data types, and Large number of data into the table and trying to figure-out the Performance with Varchar and Numeric data. But, i got some error which is i dont think should not have to be but it is. My problem is below :

I have a table :

create table sa(f1 varchar(100))

I have a Stored Procedure which Inserts 100000 data into the table :

create proc sad
as
begin
    declare @i int=0
    while @i<100000
    begin
       insert into sa values(@i)
       set @i=@i+1
    end
end


exec sad

And I have tested the following with :

select CONVERT(int,f1) from sa  //Works Fine, i tested after the Problem
select sum(convert(int,f1)) from sa  //Didn't Worked, So i tested above and Below
select sum(convert(decimal(18,2),f1)) from sa //And, it again works fine

But, When i sum Converting F1 to Int, it shows me an error.
But, when i only select Converting to Int its fine.
And, when i sum Converting F1 to decimal it works Fine.

What the SUM function data type?
On the Above data it works well with Decimal but not Int?
Why?

Im Getting the Following error

Arithmetic overflow error converting expression to data type int.

4

4 回答 4

7

您正在求和,因为INT它的范围不能容纳该总和。

DECIMAL罐头。

从 1 到 99999 的所有值的总和为 4999950000,最大 INT 值为 2147483647,不到总和的一半。

当您对 INT 求和时,您将得到一个新的 INT。当您对 DECIMAL 求和时,您将得到一个新的 DECIMAL,因此输入类型定义了输出类型。

您可以改用使用bigint,它应该“没问题”。

另外,在第二个注意事项上,请不要将数字存储为文本

于 2013-07-30T12:25:47.477 回答
4

根据 MS 文档(请参阅https://docs.microsoft.com/en-us/sql/t-sql/functions/sum-transact-sql),该SUM()函数根据数据类型返回不同类型的值您要添加的列:如果列的类型为inttinyintsmallint,则 SUM 返回类型的值int

转换为或bigint返回更大的数据类型,这解释了为什么在这种情况下您没有溢出。decimalSUM()

于 2013-07-30T12:35:59.397 回答
2

预计您已超过intSQL Server 允许的最大值 (2,147,483,647) - 请参阅https://docs.microsoft.com/en-us/sql/t-sql/data-types/int-bigint-smallint-and-tinyint-事务-sql

十进制允许高达 10^38 - 1 的更高限制(即 1 后面有 38 个零) - 请参阅https://docs.microsoft.com/en-us/sql/t-sql/data-types/decimal-和-numeric-transact-sql

但是,如果值是 type int,我不建议转换为decimal. Decimal当您的数字具有已知精度和比例的小数点后可能的数字(例如货币、百分比等)时,值很有用。正如另一位海报所建议的那样,这里最好的转换是bigint

select sum(cast(f1 as bigint)) from sa
于 2013-07-30T12:27:57.377 回答
0

int看起来您的结果总和对于、 use来说太大了bigint,还要检查int、bigint、smallint 和 tinyint (Transact-SQL)

select sum(convert(bigint,f1)) from sa
于 2013-07-30T12:27:17.723 回答