3

我在 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 错误。

4

3 回答 3

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')
   )
于 2013-05-06T15:14:24.063 回答
2

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

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)
于 2013-05-06T15:21:58.377 回答
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) ) 
于 2013-05-06T15:20:07.253 回答