如何在sql 2000的where子句里面使用case语句

时间:2013-12-17 14:23:52

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2

我有一个包含WHERE子句的查询,其中包含CASE语句(请参阅下面的代码),但它似乎无法正常工作。

select *  FROM
        details
        where orgcode in 
        (case when orgtype='P' then 
        (SELECT distinct [PCode]
        FROM   [GPOS_Extract].[dbo].[GP8288List])
        else
        0 end )

5 个答案:

答案 0 :(得分:2)

怎么样

select *  FROM details
where (orgtype <> 'P' AND orgcode = 0)
or orgcode in 
(
    SELECT distinct [PCode]
    FROM [GPOS_Extract].[dbo].[GP8288List]
)

答案 1 :(得分:1)

或试试这个:

SELECT * FROM details
WHERE details.orgcode IN
( SELECT DISTINCT
  (CASE WHEN details.orgtype='P' 
  THEN [GPOS_Extract].[dbo].[GP8288List].PCode 
  ELSE 0 END)
  FROM [GPOS_Extract].[dbo].[GP8288List] )

答案 2 :(得分:1)

我认为以下是与您的尝试相同的逻辑:

select *
FROM details
where (orgtype = 'P' and
       orgcode in (SELECT distinct [PCode]
                   FROM   [GPOS_Extract].[dbo].[GP8288List]
                  )
      ) or
      ((orgtype <> 'P' or orgtype is NULL) and orgcode = 0);

答案 3 :(得分:1)

case返回单个值。您正在尝试使用它,就像它返回结果集一样。你想要的是:

select * FROM details d
where (orgtype = 'p' 
    And exists (Select * 
                From GPOS_Extract.dbo.GP8288List
                Where PCode = d.orgcode))
    or (orgtype <> 'p' And orgcode= 0)

答案 4 :(得分:1)

怎么样,

select a.*,case when orgtype='P' then PCode else '0' end FROM
 details a
left join [GPOS_Extract].[dbo].[GP8288List] b on a.orgcode=b.PCode