select case不适用于其中一个值

时间:2017-11-14 14:43:15

标签: sql-server

为什么我的'XXX'值在此select case语句中不起作用。我希望它返回一个空白,但它返回与“RNC”相同的字符串。

SELECT SHORT_DESC =  
      CASE   
         WHEN MAIL_CODE1 <> 'RNC' THEN SHORT_DESC
         WHEN MAIL_CODE1 = 'XXX' THEN ' '
         ELSE 'Request No Contact'    
      END 
FROM (select 1 dummy) dummy
left join TMS_MAILING_1 m ON m.MAIL_CODE1 = 'XXX'--${MailCode}
  GROUP BY SHORT_DESC, MAIL_CODE1;

1 个答案:

答案 0 :(得分:3)

这个怎么样?

SELECT SHORT_DESC =  
      CASE   
         WHEN MAIL_CODE1 = 'XXX' THEN ' '
         WHEN MAIL_CODE1 <> 'RNC' THEN SHORT_DESC
         ELSE 'Request No Contact'    
      END 
FROM (SELECT 1 dummy) dummy
    LEFT JOIN TMS_MAILING_1 m ON m.MAIL_CODE1 = 'XXX'--${MailCode}
GROUP BY SHORT_DESC, MAIL_CODE1;

请记住,CASE语句中存在条件验证顺序,从第一个开始到最后一个。

返回第一个有效条件,在您的情况下为TRUE

您应该始终首先检查相等性,然后检查不相等。

此外,您的查询逻辑似乎有点奇怪。我重写了一下这样的查询:

DECLARE @PARAM NVARCHAR(MAX) = 'XXX'--${MailCode}

SELECT
    SHORT_DESC = CASE
        WHEN MAIL_CODE1 = 'XXX'
            THEN ''
        WHEN MAIL_CODE1 <> 'RNC'
            THEN SHORT_DESC
        ELSE 'Request No Contact'
    END
FROM TMS_MAILING_1
WHERE MAIL_CODE1 = @PARAM

出于测试目的,您可以使用以下代码,只需更改@PARAM变量的值,即可根据您的输入查看查询的行为。

DECLARE @PARAM NVARCHAR(MAX) = 'XXX'--${MailCode}

SELECT
    SHORT_DESC = CASE
        WHEN MAIL_CODE1 = 'XXX'
            THEN ''
        WHEN MAIL_CODE1 <> 'RNC'
            THEN 'SHORT_DESC'
        ELSE 'Request No Contact'
    END
FROM (SELECT @PARAM AS MAIL_CODE1) X
WHERE MAIL_CODE1 = @PARAM