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

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(225)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2017-06-05 View State
2015-06-05 C#中的反射
点击右上角即可分享
微信分享提示