将表达式转换为数据类型int时出错

时间:2014-10-14 15:59:46

标签: sql

我有一个调用select函数的TOTALFACTOR查询。但是,这个简单的函数会抛出错误

  

将表达式转换为数据类型int的算术溢出错误。

查询:

select wwid, TOTALFACTOR(days) 
from table A    

功能:

CREATE FUNCTION [dbo].[TOTALFACTOR] (@days int)      
RETURNS decimal(18,4)
AS              
BEGIN
    declare @total as decimal(18,4)

    if @days is NULL 
       return 0

    if (@days >= 0 and @days < 1461) 
        set @total = (@days * 0.01369863)  
    else if(@days >= 1462 and @days< 2557)
        set @total = (1461 * 0.01369863) + ((@days - 1461) * 0.018263014)
    else if(@days >= 2558 and @days< 3653)
        set @total = (1461 * 0.01369863) + ((2557 - 1462) * 0.018263014) + ((@days - 2557) * 0.01369863)

    return @total

1 个答案:

答案 0 :(得分:1)

尝试使用BIGINT

CREATE FUNCTION [dbo].[TOTALFACTOR] (@days BigInt)      
RETURNS decimal(18,4)
AS              
BEGIN
    declare @total as decimal(18,4)

    if @days is NULL 
       return 0

    if (@days >= 0 and @days < 1461) 
        set @total = (@days * 0.01369863)  
    else if(@days >= 1462 and @days< 2557)
        set @total = (1461 * 0.01369863) + ((@days - 1461) * 0.018263014)
    else if(@days >= 2558 and @days< 3653)
        set @total = (1461 * 0.01369863) + ((2557 - 1462) * 0.018263014) + ((@days - 2557) * 0.01369863)

    return @total
END