ROUND function and arithmetic overflow

遇到如下错误

Arithmetic overflow error converting expression to data type numeric.

SELECT ROUND(0.1, 0), ROUND(0.9, 2);

https://stackoverflow.com/questions/33835741/round-function-and-arithmetic-overflow

问题

In MS SQL Server, if I

SELECT ROUND(9.4, 0), ROUND(8.6, 0), ROUND(10.6, 0)

I unsurprisingly get:

9.0 9.0 11.0

But if I do

SELECT ROUND(9.6, 0)

解答

SQL takes the first parameter as the datatype, which is, in this case DECIMAL(2,1). The expected outcome, 10.0, should be of type DECIMAL(3,1) which is why you get the error.

Try:

SELECT ROUND(cast(9.6 as decimal(2,1)), 0)

then try:

SELECT ROUND(cast(9.6 as decimal(3,1)), 0)

分析

ROUND(0.9, 2);

需要进位了,0.9对应decimal(1,1)。但是进位之后,0.9变成1。其实类型变为decimal(1,0)。

decimal对应的类型(长度,小数位数)(length,scale)。

0.9数字长度为1,小数位数也是1。

1数字长度为1,小数位数是0。

SELECT ROUND(CAST(0.9 AS DECIMAL(1, 0)), 0);
原文地址:https://www.cnblogs.com/chucklu/p/9138831.html