开发者

Using Keyword [IN] with Case Expression in a SQL Statement

开发者 https://www.devze.com 2023-02-09 02:00 出处:网络
I have an query like this , but it does not work , what\'s wrong with IN keyword with CASE EXPRESSION ?

I have an query like this , but it does not work , what's wrong with IN keyword with CASE EXPRESSION ?

Select State = case c.addressId
  when in('2552','2478','2526') then 'IN' 
  when in ('9999') then 'OUT'
  else 'UNK开发者_如何学编程NOWN'
  end,
  name, time
from x;

I've use SQL Server 2008 and this is the error msg :

Incorrect syntax near the keyword 'in'.


You've got the syntax wrong. It should be CASE WHEN [COLUMN] in (...):

Select 
  case when c.addressId in('2552','2478','2526') then 'IN' 
  when c.addressId in ('9999') then 'OUT'
  else 'UNKNOWN'
  end as State,
  name, time
from contact c;


Consider using a join instead.

SELECT ISNULL(a.[State], 'UNKNOWN') [State]
    , c.[Name]
    , c.[Time]
FROM [contact] c
LEFT OUTER JOIN
(
    SELECT 2552 AddressId, 'IN' [State]
    UNION ALL SELECT 2478, 'IN'
    UNION ALL SELECT 2526, 'IN'
    UNION ALL SELECT 9999, 'OUT'
) [address] a ON a.AddressId = c.AddressId;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号