TSQL使用BIGINT进行算术溢出

前端之家收集整理的这篇文章主要介绍了TSQL使用BIGINT进行算术溢出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以为我澄清当我尝试在下面的示例中设置变量@a时,为什么会出现错误
DECLARE @a BIGINT
SET @a = 7*11*13*17*19*23*29*31
/*
ERROR:
Msg 8115,Level 16,State 2,Line 1
Arithmetic overflow error converting expression to data type int.
*/

我现在能想到的是,在内部,sql开始做数学评估乘法并将临时结果放入INT然后它将它转换为BIGINT.

但是,如果我在我的数字列表中添加1.0 *,则没有错误,因此我相信sql使用float作为临时结果,然后将其转换为BIGINT

DECLARE @b BIGINT
SET @b =   1.0  *  7*11*13*17*19*23*29*31
/*
NO ERROR
*/

坦率地说,我没有看到代码有什么问题…它很简单……

[我正在使用sql 2008]

[编辑]

感谢Nathan的link.
这是我不知道的好信息,但我仍然不明白为什么我会得到错误,为什么我要做“技巧”来获得这样一个简单的脚本.

这是我应该知道如何作为程序员处理的事情吗?

或者,这是一个错误,如果是这样,我会认为这个问题已经结束.

解决方法

当你进行这样的计算时,单个数字的存储量足以容纳该数字,即:数字(1,0).看一下这个:

Caution
When you use the +,-,*,
/,or % arithmetic operators to
perform implicit or explicit
conversion of int,smallint,tinyint,
or bigint constant values to the
float,real,decimal or numeric data
types,the rules that sql Server
applies when it calculates the data
type and precision of the expression
results differ depending on whether
the query is autoparameterized or not.

Therefore,similar expressions in
queries can sometimes produce
different results. When a query is not
autoparameterized,the constant value
is first converted to numeric,whose
precision is just large enough to hold
the value of the constant,before
converting to the specified data type.
For example,the constant value 1 is
converted to numeric (1,0),and the
constant value 250 is converted to
numeric (3,0).

When a query is autoparameterized,the
constant value is always converted to
numeric (10,0) before converting to
the final data type. When the /
operator is involved,not only can the
result type’s precision differ among
similar queries,but the result value
can differ also. For example,the
result value of an autoparameterized
query that includes the expression
SELECT CAST (1.0 / 7 AS float) will
differ from the result value of the
same query that is not
autoparameterized,because the results
of the autoparameterized query will be
truncated to fit into the numeric (10,
0) data type. For more information
about parameterized queries,see
Simple Parameterization.

http://msdn.microsoft.com/en-us/library/ms187745.aspx

编辑

这不是sql Server中的错误.在同一页面上,它指出:

The int data type is the primary integer data type in sql Server.

sql Server does not automatically promote other integer data types (tinyint,and int) to bigint.

这是定义的行为.作为程序员,如果您有理由相信您的数据会溢出数据类型,则需要采取预防措施来避免这种情况.在这种情况下,只需将其中一个数字转换为BIGINT即可解决问题.

DECLARE @a BIGINT
SET @a = 7*11*13*17*19*23*29*CONVERT(BIGINT,31)

猜你在找的MsSQL相关文章