两张表判断赋值,都是NULL惹的祸…

转发http://hi.baidu.com/laurel_2010/blog/item/5a99de3235adae92a8018e5d.html

上周五发现同步过来的两张表内容有差异。本不属于自己职责范围之内,但还是未避免对大家日后工作带来不必要麻烦性,主动要求同步了下这两张表内容。本以为很简单的问题,却发现这NULL值到底有多令人讨厌。

总体需求是:有两张表t1和t2【假设关注字段为id,name完全相同,我们可暂分析为两表格式完全一致】,其中t2的内容是由t1拷贝而来,我们要保证t2内容完全与t1一致。我们现只解决t1,t2中name不一致情况,缺省内容另外完成。

假设创建表为:
create table t1(id int,name varchar(50))
create table t2(id int,name varchar(50))
插入内容为:
insert into t2 values(1,'天上')
insert intot2values(2,'传说')
insert intot2values(3,'剑侠')
insert intot2values(4,'红警')
insert intot2values(5,'63')
insert intot2values(6,'NBA2004')

insert into t1 values(1,'天上碑')
insert intot1values(2,'勇者传说')
insert intot1values(3,'剑侠情缘3')
insert intot1values(4,'RA95')
insert intot1values(5,'凯撒大帝3')
insert intot1values(6,'NBA2004')

开始实现语句:
update t2
set name= b.name from t2 a left join t1 b on a.id=b.id and a.name<> b.name
运行结果很奇怪: t2表里的gname值全部为null,判断为NULL值也是执行如此…………

修改后语句:
updatet2
set name= b.name from t2 a left join t1b on a.id=b.id whereisnull(a.name,'') <> b.name

分析:NULL值不能直接参与比较,若字段中含有NULL值,我们最好对其进行转换后再行比较,在这里我们比较巧妙地运用了ISNULL的判断输出结果值来进行结果比较。
关于update的语法可参见其他文章。

附注:貌似这个也可以

update t2
set name= t1.name from t1,t2
where t1.id=t2.id and t1.name<>t2.name

原文地址:https://www.cnblogs.com/sumsen/p/2525471.html