Using Keyword [IN] with Case Expression in a SQL Statement
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;
精彩评论