简体   繁体   中英

How to use case statement inside where clause of sql 2000

I have a query that contains a WHERE clause with a CASE statement in it (See code below), somehow it doesn't seem to work.

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

How about

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

Or try this:

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

I think the following is the logic that is equivalent to your attempt:

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

case returns a single value. You are trying to use it as though it returns a result set. What you want is:

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)

what about this,

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

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