我需要使用#b table的col4中的值更新#a表中的col2。如果col4中的值已存在于col2中,则不应更新col2。在这种情况下,因为#a表中已存在11,所以#a表中的1不应更新。
以下代码工作正常 -
update a
set a.col2 = b.col4
from #a as a
inner join #b as b
on a.col1 = b.col3 and b.col4 not in (select col2 from #a where col2 is not null)
问题是当我使用WHERE EXISTS而不是NOT IN -
时update a
set a.col2 = b.col4
from #a as a
inner join #b as b
on a.col1 = b.col3
where not exists(select 1 from #b as c where c.col4 = a.col2 and a.col2 is not null)
您可以看到此查询更新了所有值,包括11.在这种情况下,因为#a表中已存在11,所以#a表中不应更新1。
有人能说出我做错了什么以及为什么这里的EXISTS不起作用?
答案 0 :(得分:1)
如果您使用#a
代替not exists
而不是#b
,它可能会按预期运行。等价的not exists
子句更像是这样:
update a
set a.col2 = b.col4
from #a a inner join
#b b
on a.col1 = b.col3
where not exists (select 1
from #a a2
where a2.col2 = b.col4 and a2.col2 is not null
);