sql-server - SQL Server 转换因算术溢出而失败

标签 sql-server precision

根据SQL Server 2008联机丛书中关于小数和数字数据类型的条目,精度为:

p (precision) The maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The precision must be a value from 1 through the maximum precision of 38. The default precision is 18.

但是,下面的第二个选择失败,出现“将 int 转换为数字数据类型时出现算术溢出错误。”

SELECT CAST(123456789 as decimal(9,0))
SELECT CAST(123456789 as decimal(9,1))

最佳答案

看这里:http://msdn.microsoft.com/en-us/library/aa258832(SQL.80).aspx

decimal[(p[, s])]

p (precision) Specifies the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The precision must be a value from 1 through the maximum precision. The maximum precision is 38. The default precision is 18.

s (scale) Specifies the maximum number of decimal digits that can be stored to the right of the decimal point. Scale must be a value from 0 through p. Scale can be specified only if precision is specified. The default scale is 0; therefore, 0 <= s <= p. Maximum storage sizes vary, based on the precision.

当使用:decimal(p,s) 时,将p 视为您要存储的总位数(无论小数点左边还是右边) , 和 s 作为这些 p 数字中有多少应该在小数点的右边。

DECIMAL(10,5)=     12345.12345
DECIMAL(10,2)=  12345678.12
DECIMAL(10,10)=         .1234567891
DECIMAL(11,10)=        1.1234567891

您的示例代码失败了:

SELECT CAST(123456789 as decimal(9,1))

因为:

9=精度(小数点左右的总位数)
1=scale(小数点右边的总位数)
(9-1)=8(小数点左边的总位数)

您的值 123456789 需要小数点左边的 9 位数字。你将需要 decimal(10,1) 或者只是 decimal(9,0)

关于sql-server - SQL Server 转换因算术溢出而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2884091/

相关文章:

sql - 如何在 SQL Server 中存储 token

sql-server - 如何增加在 Microsoft SQL Server 2005/2008 中使用 msdb.dbo.sp_send_dbmail 发送的电子邮件允许的最大附件大小

awk 和数值小于 1.7e-308 的数值比较

php - 货币的浮点精度 : using "round" function in MySQL query vs PHP vs Javascript

java - (Java) 如何使用扩展精度算术来处理更大的阶乘?

android - ARCore 尺度估计精度

python - 将 Python 脚本连接到 SQL Server

sql-server - 使用 IF IsNumeric 作为参数

sql-server - 我应该创建使用数据库图表所需的支持对象吗?

java - 全局多标签性能评估的平均精度/召回率是否正确?