简体   繁体   中英

Using CASE with IN rather than =

I want to do something like the following but I can't find good way to make it happen. The following:

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

throws an error:

Incorrect syntax near the keyword 'case'

It works with = but I lose the benefits of in , obviously. Is it not possible to do this?

You can't use CASE inside IN . CASE is an expression that returns up to a single value; it can't be used for controlling flow like the CASE statement can in other languages, or for returning multiple values (as IN does).

I would re-write it this way:

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
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM