假设我有2个名为aTable1,aTable2的表
aTable1已将userID设置为identity,并包含以下数据:
userID email FirstName LastName 1 NULL C CC 2 NULL D DD 3 a@yahoo.com A AA 4 b@yahoo.com B BB 5 e@yahoo.com E EE 6 f@yahoo.com NULL NULL 7 g@yahoo.com NULL NULL
aTable2包含以下数据:
userID email FirstName LastName Title 3 a@yahoo.com A AA student 4 b@yahoo.com B BB student 5 e@yahoo.com E EE student NULL NULL C CC dean NULL NULL D DD advisor NULL f@yahoo.com NULL NULL student2 NULL g@yahoo.com NULL NULL student3
我想基于aTable1更新aTable2.userID,但是知道2个表中都有空值,所以我喜欢这样:
set ANSI_NULLS off update aTable2 set aTable2.userID = a.userID from aTable a, aTable2 b where a.FirstName = b.FirstName and a.LastName = b.LastName and a.email = b.email
但是,此更新不会更新所有的userID,实际上,它只会更新电子邮件不等于null的那些,但是我已经将ANSI_NULLS设置为off。我做错什么了?
要使更新查询生效,您可以尝试执行以下操作:
UPDATE a2 SET userId = a.UserId FROM aTable2 a2 JOIN aTable1 a ON ISNULL(a.Email,'NULL') = ISNULL(a2.Email,'NULL') AND ISNULL(a.FirstName,'NULL') = ISNULL(a2.FirstName,'NULL') AND ISNULL(a.LastName,'NULL') = ISNULL(a2.LastName,'NULL')
当值为NULL时,我已将值任意设置为“ NULL”-使用一些不会在您的数据中出现的独特值,以确保您不会收到误报。
我还看到了在JOIN中使用OR条件并检查两个值是否均为NULL的其他解决方案:
((a.Email = a2.Email) OR (a.Email IS NULL AND a2.Email IS NULL)) ...
祝你好运。