简体   繁体   中英

Subquery in CASE statement under the WHERE clause (using IN)

I have the query below giving me this error:

Msg 512, Level 16, State 1, Line 5
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

I'm getting the error from the subquery in the WHERE clause.

When you see '5,137' that will be a variable taking its place. And Select val FROM DB01.dbo.f_split('5,137',',') will return the list of separated values as a result.

Another thing I tried was placing ('5','137') in place of (Select val FROM DB01.dbo.f_split('5,137',',')) but I was getting an error on the comma between 5 and 137.

Any ideas? All help is greatly appreciated.

select 
    @Total_Orders = sum(a11.ORDER_CNT)
from 
    a11
join 
    a12 on (a11.STORE_ID = a12.STORE_ID)
join 
    a13 on (a12.CLIENT_ID = a13.CLIENT_ID)
join 
    a14 on (a11.ACTIV_DATE_ID = a14.DATE_ID)
join 
    a15 on (a13.PARENT_ID = a15.PARENT_ID)
where 
    a15.PARENT_DESC = 'Vanilla'
    AND a13.CLIENT_ID IN 
    (
    CASE WHEN '5,137'<>'All'
    THEN (Select val FROM DB01.dbo.f_split('5,137',','))
    ELSE (a13.CLIENT_ID)
    END
    )
    AND a14.DATE between CONVERT(char(10), '2015-12-27T00:00:00-05:00',126) and CONVERT(char(10), '2016-01-02T23:59:59-05:00',126)
group by a13.PARENT_ID

CASE expressions can only return single scalar values. Separate the two legs and us OR :

AND ('5,137' = 'All'
    OR a13.CLIENT_ID IN (Select val FROM DB01.dbo.f_split('5,137',',')))

CASE does not work like if in procedural languages. CASE only returns a single value. So you'll have to rewrite your WHERE clause along the lines of:

WHERE    ('5,137'<>'All'
         AND  a13.CLIENT_ID IN (Select val FROM DB01.dbo.f_split('5,137',',')))
      OR '5,137'='All'

I hope I understand correctly that '5,137' is a placeholder, which will be filled in with different values. Otherwise it's pointless to compare it to 'All'

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