在sql server 2008 R2中与内连接一起使用时存在不起作用

时间:2015-09-03 02:19:11

标签: sql-server-2008

我需要使用#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不起作用?

1 个答案:

答案 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
                 );