db2 temp table" with ... as()"算术溢出

时间:2014-05-15 17:28:52

标签: sql math db2 overflow temporary

我在用户定义的函数中使用以下临时表构造来计算斐波纳契数。 不幸的是,temp-table构造给了我一个高值的算术溢出错误,但我不知道如何更改临时表正在使用的数据类型......

WITH FIB_SQL(I, RES_1, RES) AS (
    SELECT 1, 0, 1 FROM SYSIBM.SYSDUMMY1
    UNION ALL
    SELECT I+1, RES, RES+RES_1 FROM FIB_SQL WHERE I < 50
)
SELECT MAX(RES) FROM FIB_SQL;

适用于“我在哪里&lt; 40”但不适用于“我在哪里&lt; 50”

1 个答案:

答案 0 :(得分:2)

RESRES_1中的值足够大,当您对2个值求和时,它会产生一个大于数据类型将存储的值。

假设数据类型当前是整数,您可以将数据类型转换为bigint,如下所示:

WITH FIB_SQL(I, RES_1, RES) AS (
    SELECT 1, cast(0 as bigint), cast(1 as bigint) FROM SYSIBM.SYSDUMMY1
    UNION ALL
    SELECT I+1, RES, cast(RES as bigint) + cast(RES_1 as bigint) FROM FIB_SQL WHERE I < 50
)
SELECT MAX(RES) FROM FIB_SQL;

有关整数的更多信息(大整数的范围是-2147483648到+2147483647)http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=%2Fcom.ibm.db2z9.doc.sqlref%2Fsrc%2Ftpc%2Fdb2z_integer.htm

VS。 bigint(大整数范围是-9223372036854775808到+9223372036854775807)http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=%2Fcom.ibm.db2z9.doc.sqlref%2Fsrc%2Ftpc%2Fdb2z_biginteger.htm

修改 使用BIGINT的此解决方案将允许您升级到I&lt; 92,但我&lt; 93仍将给出算术溢出错误,b / c则超出允许的BIGINT值范围。

如果您需要使用BIGINT范围之外的值,请检查decimaldecfloat数据类型。 http://www-01.ibm.com/support/knowledgecenter/SSEPEK_10.0.0/com.ibm.db2z10.doc.intro/src/tpc/db2z_numericdatatypes.dita

使用十进制数据类型的示例,这使您可以达到I&lt; 150,返回9969216677189303386214405760200:

WITH FIB_SQL(I, RES_1, RES) AS (
    SELECT 1, CAST(0.0 AS decimal(31, 0)), CAST(1 AS decimal(31, 0))
    UNION ALL
    SELECT I+1, RES, CAST(RES +  RES_1 AS decimal(31, 0)) FROM FIB_SQL WHERE I < 150
)
SELECT MAX(RES) FROM FIB_SQL 
--OPTION (MAXRECURSION 150) --in SQL Server this is needed to increase the max recursion setting, not sure if this is needed in DB2 or not.
;