如何在dateadd中处理月份值

时间:2013-04-29 06:32:40

标签: sql sql-server-2008

我知道问题是什么,但有人可以建议如何解决此问题。

问题是,当我在dateadd中计算数月时,我的价值超过98540 :(

declare @Basepool int =10000000
declare @transactioncount bigint =1
declare @Monthnum int=1
declare @ContractId int=1

select CASE @Basepool 
            WHEN 0 THEN 'N/A'
            WHEN -1 THEN 'N/A'
            ELSE CASE 
                    WHEN SUM(SUM(@TransactionCount)) OVER (Partition by @ContractId) > @Basepool THEN 'IN-OVERAGE'
                    --WHEN SUM(SUM(B.TransactionCount)) OVER (Partition by @ContractId) + (SUM(SUM(B.TransactionCount))  OVER (Partition by @ContractId)/MonthNum) > U.BasePool THEN DATEADD(MM, 1, GETDATE())
                    ELSE  CONVERT(VARCHAR(20),DATEADD(MM,CAST(ROUND((@Basepool - SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId)) 
                                /(SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId)/@Monthnum),0) as INT), GETDATE()),101)

                    --(basepool - sumcontract) / (sumcontract/monthNum ) is the expected months to reach overage
                END 

            END AS  ExpectedDate

2 个答案:

答案 0 :(得分:0)

你的@Basepool变量有很长的值,由INT溢出。 只需尝试以下更正的代码。

declare @Basepool INT =10000
declare @transactioncount bigint =1
declare @Monthnum int=1
declare @ContractId int=1

select CASE @Basepool 
            WHEN 0 THEN 'N/A'
            WHEN -1 THEN 'N/A'
            ELSE CASE 
                    WHEN SUM(SUM(@TransactionCount)) OVER (Partition by @ContractId) > @Basepool THEN 'IN-OVERAGE'
                    ELSE  CONVERT(VARCHAR(20),DATEADD(MM,CAST(ROUND((@Basepool - SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId)) 
                                /(SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId)/@Monthnum),0) as INT), GETDATE()),101)
                END 

       END AS  ExpectedDate

答案 1 :(得分:0)

首先,我可以添加到getdate()的最长月份是

select dateadd(mm, 95840, getdate())

您需要的是一种处理异常情况的方法,其中要添加的月数大于限制。

试试这个:

select DATEADD(MM
    , case when CAST(ROUND((@Basepool - SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId))/(SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId)/@Monthnum),0) as INT)
        > datediff(mm, getdate(), '9999-12-31')
        then datediff(mm, getdate(), '9999-12-31')
        else CAST(ROUND((@Basepool - SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId))/(SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId)/@Monthnum),0) as INT)
        end
    , GETDATE())

从查询中获取值后,您需要处理'9999-12-XX'。