在where子句sql中选择inside case语句

时间:2013-05-06 15:11:00

标签: sql sql-server tsql

我在where子句中编写了一个case子句,该子句在没有任何子查询的情况下正常工作,但它不能用于子查询

例如

declare @isadmin varchar(5) = 'M'

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

工作正常。

然而,这似乎不起作用 -

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)

任何建议或这都是2008年的t-sql错误。

3 个答案:

答案 0 :(得分:2)

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

已编辑显示如何使用多个条件

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

答案 1 :(得分:2)

我相信你收到的错误是“Subquery返回的值超过1”。因此,在那之后你不能返回多个值。 您应该将查询重写为以下内容:

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)

答案 2 :(得分:1)

这应该有用(虽然它不是问题的直接答案):

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