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.
这是我不知道的好信息,但我仍然不明白为什么我会得到错误,为什么我要做“技巧”来获得这样一个简单的脚本.
这是我应该知道如何作为程序员处理的事情吗?
或者,这是一个错误,如果是这样,我会认为这个问题已经结束.
解决方法
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
编辑
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)