Pradyut Bhattacharya
Pradyut Bhattacharya

Reputation: 5748

select inside case statement in where clause tsql

I have written a case condition inside where clause which is working fine without any sub queries, but it is not working with sub queries

for example

declare @isadmin varchar(5) = 'M'

select * from Aging_calc_all a where a.AccountNumber in 
(case @isadmin when 'M' then 1 else 0 end)

which is working fine.

However this does not seem to work -

select * from Aging_calc_all a where a.AccountNumber in 
(case @isadmin when 'M' then (select AccountNumber from ACE_AccsLevelMaster where AssignedUser=7) else 0 end)

Any suggestions or this is a t-sql bug in 2008.

Upvotes: 3

Views: 10362

Answers (3)

Dewfy
Dewfy

Reputation: 23614

select * from Aging_calc_all a where a.AccountNumber in (
   SELECT AccountNumber 
     from ACE_AccsLevelMaster 
     where AssignedUser=7 AND @isadmin = 'M'
   UNION ALL select 0 where @isadmin <> 'M'
   )

EDITED To show how use multiple criteria

select * from Aging_calc_all a where a.AccountNumber in (
   SELECT AccountNumber 
     from ACE_AccsLevelMaster 
     where AssignedUser=7 AND @isadmin = 'M'
   -- case to select from another table:
   UNION ALL select * from ANOTHER_TABLE where @isadmin = 'A' 
   -- case to select from const set (1, 2, 3):
   UNION ALL select * from ( 
      select 1 union all select 2 union all select 3) x where @isadmin = 'B' 
   -- case to show how 'else' work
   UNION ALL select 0 where @isadmin not in( 'M', 'A', 'B')
   )

Upvotes: 2

AdamL
AdamL

Reputation: 13141

The error you're receiving is "Subquery returned more than 1 value", I believe. So you can't return multiple values after THEN. You should rewrite your query to something like this:

select 
    * 
from Aging_calc_all a 
where 
    (@isadmin='M' and a.AccountNumber in (select AccountNumber from ACE_AccsLevelMaster where AssignedUser=7))
    or 
    (@isadmin<>'M' and a.AccountNumber=0)

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460058

This should work(although it's not a direct answer of the question):

SELECT * 
FROM   aging_calc_all a 
WHERE  ( @isadmin <> 'M' AND a.accountnumber = 0 ) 
    OR ( @isadmin =  'M' AND a.accountnumber IN (SELECT accountnumber 
                                     FROM   ace_accslevelmaster 
                                     WHERE  assigneduser = 7) ) 

Upvotes: 1

Related Questions