根据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/