为什么 SQL Server 在将 int 转换为数据类型 numeric 时会抛出算术溢出错误?
运行此代码时,SQL Server Management Studio 抛出一个错误:
declare @percentage numeric(3,2)
set @percentage = cast(15 as numeric(3,2))
但是当我将数字声明更改为
declare @percentage numeric(4,2)
set @percentage = cast(15 as numeric(4,2))
一切正常时。
数字数据类型有限制吗?
I have an error being thrown by SQL Server Management Studio when running this code:
declare @percentage numeric(3,2)
set @percentage = cast(15 as numeric(3,2))
but when I change numeric declaration to
declare @percentage numeric(4,2)
set @percentage = cast(15 as numeric(4,2))
everything goes fine.
Is there a limitation for numeric data type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
数字定义了总位数,然后是小数点后的数字。
数字(3,2) 最多只能容纳 9.99。
Numeric defines the TOTAL number of digits, and then the number after the decimal.
A numeric(3,2) can only hold up to 9.99.
让我们看看,数字 (3,2)。这意味着您有 3 个数据位,其中两个位于小数点右侧,仅留一位位于小数点左侧。 15 小数点左边有两位。顺便说一句,如果您可能有 100 作为值,我会将其增加到数字 (5, 2)
Lets see, numeric (3,2). That means you have 3 places for data and two of them are to the right of the decimal leaving only one to the left of the decimal. 15 has two places to the left of the decimal. BTW if you might have 100 as a value I'd increase that to numeric (5, 2)
NUMERIC(3,2)
表示:共3位,小数点后2位。所以小数点前只有一位小数。尝试
NUMERIC(5,2)
- 小数点前三位,小数点后两位。NUMERIC(3,2)
means: 3 digits in total, 2 after the decimal point. So you only have a single decimal before the decimal point.Try
NUMERIC(5,2)
- three before, two after the decimal point.精度和比例经常被误解。在 numeric(3,2) 中,您需要总共 3 位数字,但小数点右边 2 位。如果你想要15 => 15.00,因此前导 1 会导致溢出(因为如果您想要小数点右侧有 2 位数字,则左侧仅剩下一位数字的空间)。对于 4,2 没有问题,因为所有 4 个数字都适合。
Precision and scale are often misunderstood. In numeric(3,2) you want 3 digits overall, but 2 to the right of the decimal. If you want 15 => 15.00 so the leading 1 causes the overflow (since if you want 2 digits to the right of the decimal, there is only room on the left for one more digit). With 4,2 there is no problem because all 4 digits fit.
这是一个很老的问题,但我想我应该在这里添加这个以便完成:有一个 SQL Server 数据库设置可以影响查询并引发此错误。
将其设置为 ON 将导致此确切错误,因为结果不适合结果数据类型。
例如,将其设置为 ON 并运行
将引发此错误。
更多信息: https:// /learn.microsoft.com/en-us/sql/t-sql/statements/set-numeric-roundabort-transact-sql
还有另一种设置方法:
Pretty old question but I thought I'd add this here for completion sake: There is a SQL Server database setting which can affect queries and throw this error.
Setting this to ON will cause this exact error is the result does not fit the resulting datatype.
For example, setting this to ON and running
will throw this error.
More Info: https://learn.microsoft.com/en-us/sql/t-sql/statements/set-numeric-roundabort-transact-sql
Also another way to set it: