开发者

SQL CASE statement mutliple GUID's = same value

I have a case statement that is as follows:

CASE id
  WHEN '9FDAC41CBF5ED6E3758' THEN 'Invalid' 
  WHEN '5EBF056B16E7593' THEN 'Invali开发者_如何学编程d' 
  WHEN 'EEDC43399D10F44A19E293BB' THEN 'Invalid'
  WHEN '2322' THEN 'No'
  ELSE 'Yes'
END AS [Test]  

Is it possible to put the 3 when clauses in 1 when clause since they are essentially returning the same value?


Yes. See below.

CASE WHEN [SomeColumn] = '9FDAC41CBF5ED6E3758' 
    OR [SomeColumn] = '5EBF056B16E7593' 
    OR [SomeColumn] = 'EEDC43399D10F44A19E293BB'
THEN 'Invalid'
WHEN '2322' THEN 'No'
ELSE 'Yes'END AS [Test]  

You could also use IN

CASE WHEN [SomeColumn] IN('9FDAC41CBF5ED6E3758', '5EBF056B16E7593', 'EEDC43399D10F44A19E293BB')
THEN 'Invalid'
WHEN '2322' THEN 'No'
ELSE 'Yes'END AS [Test]  


CASE 
    WHEN [SomeColumn] IN ('9FDAC41CBF5ED6E3758', '5EBF056B16E7593', 'EEDC43399D10F44A19E293BB') THEN 'Invalid'
    WHEN [SomeColumn] = '2322' THEN 'No'
    ELSE 'Yes'
END AS [Test]  

Note: I've included your "no" condition too...


If you are going to have a very long list of "invalid" guids, then you could store them in a separate table (INVALID_GUIDS in my example). If you did that, your statement would look like this:

CASE 
    WHEN [SomeColumn] IN (SELECT GUID FROM INVALID_GUIDS) THEN 'Invalid'
    WHEN [SomeColumn] = '2322' THEN 'No'
    ELSE 'Yes'
END AS [Test]  


CASE WHEN:
    WHEN id IN ('9FDAC41CBF5ED6E3758', '5EBF056B16E7593', 'EEDC43399D10F44A19E293BB') THEN 'Invalid' 
 ELSE 'Yes'
END AS [Test] 


I propose rather than a hard-coded list of GUIDs that these should rather be in a table somewhere, then you can use a SQL syntax as follows:

SELECT MyTable.ColumnA ...
WHERE MyTable.GUID NOT IN
(SELECT InvalidGUID FROM InvalidGUIDs)


A slight alternative to JosephStyons answer in case you don't prefer an inline query inside a case statement.

SELECT
    CASE 
        WHEN ig.Guid IS NOT NULL THEN 'Invalid'
        WHEN [SomeColumn] = '2322' THEN 'No'
        ELSE 'Yes'
    END AS [Test]
FROM 
     YourTable yt
     LEFT JOIN INVALID_GUIDS ig
     ON yt.SomeColumn = ig.GUID
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜