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);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值