2013-04-29 59 views
1

我知道問題是什麼,但任何人都可以請建議如何解決此查詢。如何處理dateadd中的月份值

的問題是,當我在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 
+0

如果查詢在2013-04-29上執行,它應該是95840而不是98540。 – 2013-04-29 06:56:25

回答

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'。

+0

非常感謝。這解決了我的問題:) – 2013-04-29 12:25:45

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 
+0

我知道那是問題所在。我需要將basepool值設爲10000000.數據無法更改。我必須更改代碼 – 2013-04-29 06:51:22

+0

好吧,我會嘗試給我幾分鐘。 – Anvesh 2013-04-29 06:52:32

+0

我最多隻能添加95841個月。 – Anvesh 2013-04-29 06:59:31

相關問題