SQL Server:Case语句无法按条件执行

时间:2018-08-02 13:32:53

标签: sql sql-server

我有以下SQL语句:

SELECT 
    B.ID
    CASE 
       WHEN (B.NAME <> E.NAME OR (B.NAME IS NULL AND E.NAME IS NOT NULL))
          THEN 'NAME DOES NOT MATCH' 
    END AS NAME_ERROR, 
    B.NAME AS B_NAME, 
    E.NAME AS E_NAME
FROM 
    EMPLOYEE E, BACKUP B
WHERE 
    E.ID = B.ID

我正在使用上面的SQL,但是我想要的是NAME_ERROR列以及B_NAMEE_NAME如果匹配,则不应完全选择。

当前,如果它们匹配,则会选择B_NAMEE_NAME以及NAME_ERROR列,该列中填充了我不想要的空值。

谢谢

4 个答案:

答案 0 :(得分:0)

添加

ELSE ''

转到您的CASE表达式

答案 1 :(得分:0)

您错过了另一个查询

SELECT B.ID,
CASE WHEN (B.NAME <> E.NAME OR (B.NAME IS NULL AND E.NAME IS NOT NULL))
THEN 'NAME DOES NOT MATCH' else 'nothing' END AS NAME_ERROR, 
B.NAME AS B_NAME, E.NAME AS E_NAME
FROM EMPLOYEE E, BACKUP B
WHERE E.ID = B.ID

答案 2 :(得分:0)

您不能使用case表达式来执行动态SQL查询,而是可以执行以下操作:

SELECT B.ID, (CASE WHEN (B.NAME <> E.NAME OR (B.NAME IS NULL AND E.NAME IS NOT NULL)
                        )
                   THEN 'NAME DOES NOT MATCH' 
                   ELSE CONCAT (B.NAME, ' ', E.NAME)
              END) AS NAME
FROM EMPLOYEE E INNER JOIN
     BACKUP B
     ON E.ID = B.ID;

但是,这不能解决您的实际问题,但这是替代方法。

答案 3 :(得分:0)

动态SQL的替代方法是使用IF:

IF someCondition='true'
     SELECT Query A
ELSE
     SELECT Query B