首页 > 解决方案 > 评估为空校正的列

问题描述

表格1:

ID   email
A    a@gmail.com

表 2:

ID   email2        email3   email4
A    a@gmail.com   null     ab@gmail.com

询问:

select T1.ID, T1.email, 
case when T1.email<>T2.email2 then T2.email2 end email2,
case when T1.email<>T2.email3 and T2.email2<>T2.email3 then T2.email3 end email3,
case when T1.email<>T2.email4 and T2.email2<>T2.email4 and T2.email3<>T2.email4 then T2.email4 end email4
from t1 
left join t2 on t1.id=t2.id

输出:

ID  email         email2   email3   email4
A   a@gmail.com   null     null     null

预期输出:

ID  email         email2   email3   email4
A   a@gmail.com   null     null     ab@gmail.com

看起来email4评估为空,因为email3它是空的。我想我明白为什么按照为什么 NULL = NULL 在 SQL server 中评估为 false,但是我有一种简单的方法可以避免这种情况发生吗?真正的查询要复杂得多,如果我isnull(value,'')在 case 语句中的每个变量周围添加类似的东西以避免与空值进行比较,那可能会变得很多。

请注意,我无权更改ansi_nulls设置等

标签: sqlsql-server

解决方案


因为NULL意味着

我不知道。

所以你可以尝试IS NULL在每一CASE WHEN列中添加检查

 CREATE TABLE Table1(
  ID VARCHAR(50),
  email VARCHAR(50)
);

INSERT INTO Table1 VALUES ('A','a@gmail.com');

CREATE TABLE Table2(
  ID  VARCHAR(50),
  email2 VARCHAR(50),
   email3 VARCHAR(50),
    email4 VARCHAR(50)
);



INSERT INTO Table2 VALUES ('A','a@gmail.com',null,'ab@gmail.com');

查询 1

select T1.ID, T1.email, 
case when T1.email<>T2.email2  then T2.email2 end email2,
case when T1.email<>T2.email3 and T2.email2<>T2.email3 then T2.email3 end email3,
case when (T1.email<>T2.email4 OR T1.email IS NULL) and 
            (T2.email2<>T2.email4  OR T2.email2 IS NULL)  and 
            (T2.email3<>T2.email4  OR T2.email3 IS NULL)  then T2.email4 end email4
from Table1 t1 
left join Table2 t2 on t1.id=t2.id

结果

| ID |       email | email2 | email3 |       email4 |
|----|-------------|--------|--------|--------------|
|  A | a@gmail.com | (null) | (null) | ab@gmail.com |

推荐阅读