【问题标题】:SQL Function Error: Arithmetic OverflowSQL 函数错误:算术溢出
【发布时间】:2015-08-19 11:36:48
【问题描述】:

我有一个非常简单的函数来计算和格式化浮点数:

ALTER FUNCTION GetUrbanHours 
(
-- Add the parameters for the function here
@driverID int
)
RETURNS int
AS
BEGIN
DECLARE @Result float = 0

SELECT @Result = 
    FORMAT(
        SUM(CONVERT(float, 
            CONVERT(bigint, RouteSummary.UrbanNightSeconds + RouteSummary.UrbanDaySeconds))/(60*60)),
        '##,##0.00')
    FROM RouteSummary WHERE DriverID = @driverID

-- Return the result of the function
RETURN @Result

END

当我使用给定参数调用函数时,我收到以下错误:

Msg 8115, Level 16, State 2, Line 6
Arithmetic overflow error converting expression to data type int.
Msg 8114, Level 16, State 5, Line 9
Error converting data type varchar to float.

当我提取 SELECT 语句并打印 @Result 时,我得到了预期的结果。我的问题是什么?

编辑

我将函数改写如下:

ALTER FUNCTION GetUrbanHours 
(
@driverID int
)
RETURNS nvarchar(50)
AS
BEGIN
DECLARE @Result nvarchar(50)
DECLARE @SumSeconds bigint
DECLARE @SumHours float

SELECT @SumSeconds = 
    SUM(RouteSummary.UrbanNightSeconds + RouteSummary.UrbanDaySeconds)
    FROM RouteSummary WHERE DriverID = @driverID
IF @SumSeconds != NULL
BEGIN
    SET @SumHours = CONVERT(float, @SumSeconds) / (60*60)
    SET @Result = 
        FORMAT(@SumHours, '##,##0.00')
END
RETURN @Result

END

当我给出一个从 RouteSummary 表返回行的参数时,我得到 NULL。当我给出一个不返回任何行的参数时,我得到“消息 8115,级别 16,状态 2,第 1 行算术溢出错误,将表达式转换为数据类型 int。”现在有什么问题?还有一种方法可以识别错误消息所指的函数中的行吗?为什么我不能使用 SQL Studio 调试器单步执行该函数?

【问题讨论】:

  • 尝试将返回类型更改为 BIGINT
  • 打印时select的输出是什么?

标签: tsql sql-function


【解决方案1】:

要解决第一个错误,不要给变量赋值。第二个错误是由您使用 TSQL FORMAT 语句引起的。格式语句返回 VARCHAR 而不是 FLOAT。有关 FORMAT 命令的信息,请参阅此链接。 MSDN link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多