2013-12-09 27 views
0

我想要做類似以下的事情,但是我無法找到實現它的好方法。以下:在IN中使用CASE而不是=

where i.expirationdate in 
    case when i.locationstate = 'ca' then 
     case when datepart(month, @RunDate) < 3 then 
       (dateadd(day, 60, @RunDate)) 
      when datepart(month, @RunDate) = 3 then 
       (dateadd(day, 60, @RunDate), dateadd(day, 90, @RunDate)) 
      else 
       (dateadd(day, 90, @RunDate)) 
     end 
    else 
      (dateadd(day, 45, @RunDate)) 
    end 

拋出一個錯誤:

Incorrect syntax near the keyword 'case'

它與=但我失去的in的好處,效果顯着。這是不可能的嗎?

回答

4

您不能在IN內使用CASECASE表達式,其返回值高達單值值;它不能用於控制流程,如CASE陳述可以用其他語言或用於返回多個值(如IN所做的那樣)。

我會重新寫這樣說:

DECLARE @m TINYINT = DATEPART(MONTH, @RunDate), 
     @d45 DATETIME = DATEADD(DAY, 45, @RunDate), 
     @d60 DATETIME = DATEADD(DAY, 60, @RunDate), 
     @d90 DATETIME = DATEADD(DAY, 90, @RunDate); 

SELECT 
    ... 
WHERE 
(
    i.locationstate = 'ca' AND 
    (
     (@m < 3 and i.expirationdate = @d60) 
    OR (@m = 3 and i.expirationdate IN (@d60, @d90)) 
    OR (@m > 3 AND i.expirationdate = @d90) 
) 
) 
OR 
(
    i.locationstate <> 'ca' AND i.expirationdate = @d45 
); 
+0

謝謝。不過,第二種可能的結果確實有多個值。 – aw04

+0

@ aw04對不起,我看不到它 - 回車是你的朋友 –