[英]Arithmetic overflow error converting varchar to data type numeric in SQL Server
I getting an "Arithmetic Overflow" error when trying this conversion: 尝试进行此转换时,出现“算术溢出”错误:
select convert(numeric(10, 4), '4236575.320000000000000000')
But it can convert for numeric without decimal by using this: 但是可以使用以下命令将其转换为不带小数的数字:
select convert(numeric, '4236575.320000000000000000')
What would be the reason for this? 这是什么原因呢?
The value 4236575.320000000000000000
requires a datatype of NUMERIC(25, 18)
because you have 7 digits before decimal and 18 after it. 值4236575.320000000000000000
要求数据类型为NUMERIC(25, 18)
4236575.320000000000000000
NUMERIC(25, 18)
因为小数点前有7位数字,小数点后有18位。
Having said that, you can use smaller precision and scale as long as the portion before decimal could be stored without truncation: 话虽如此,只要可以存储小数点前的部分而不会被截断,则可以使用较小的精度和小数位数:
SELECT str
, CONVERT(NUMERIC(8, 1), str) AS [ddddddd.d]
, CONVERT(NUMERIC(7, 0), str) AS [ddddddd]
, CONVERT(NUMERIC(9, 2), str) AS [ddddddd.dd]
FROM (VALUES
('4236575.320000000000000000')
) AS tests(str)
Result: 结果:
str | ddddddd.d | ddddddd | ddddddd.dd
4236575.320000000000000000 | 4236575.3 | 4236575 | 4236575.32
When you specify numeric(10,4)
you are telling SQL Server to use a precision of 10 ie the number of digits stored from both sides of the decimal point and a scale of 4 ie 4 digits to the right of the decimal point. 当您指定numeric(10,4)
您将告诉SQL Server使用精度10,即从小数点两侧存储的位数,以及小数位数为4(即小数点右边的4位)。
This effectively means that the maximum number can be 999999.9999 (with 6 digits to the left of the decimal point and 4 digits to the right) which is smaller than 4236575.3280 which would overflow the storage. 这实际上意味着最大数量可以是999999.9999(小数点左边的6位数字,右边的4位数字)小于4236575.3280,这会使存储空间溢出。 Importantly the data that would be lost is the most significant digit rather than the least significant digit and this is why it fails. 重要的是,将丢失的数据是最高有效位数,而不是最低有效位数,这就是为什么它会失败。
You will notice that the following all succeed: 您会注意到以下所有成功:
select convert(numeric(11, 4), '4236575.320000000000000000')
select convert(numeric(10, 3), '4236575.320000000000000000')
select convert(numeric(8, 1), '4236575.320000000000000000')
which all allow for 7 digits to the left of the decimal point. 所有这些都允许小数点左边的7位数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.