删除SQL Server中两个表之间的交集

时间:2016-09-15 19:27:41

标签: sql sql-server

我想从#temp_scoring中删除匹配的帐户(在ID和acct_num上匹配),但最终删除了表#temp_scoring中的所有行。这是代码:

delete from #temp_scoring
where exists (
 select * from #temp_edu te
 where te.ID = ID
 and te.acct_num = acct_num)

作为旁注,我会为#temp_scoring创建一个别名,但是当我这样做时它给了我一个语法错误。

2 个答案:

答案 0 :(得分:1)

DELETE s
FROM
    #temp_scoring s
    INNER JOIN #temp_edu te
    ON s.ID = te.ID
    AND s.acct_num = te.acct_num

您可以使用加入

进行删除

答案 1 :(得分:0)

您的问题是列名:

delete from #temp_scoring
where exists (
 select * from #temp_edu te
 where te.ID = ID  --- Here ID means te.ID
 and te.acct_num = acct_num  -- and acct_num means te.acct_num
)

要明确ID = te.ID因为那是ID最近的封闭范围。

你可能想要这个

delete ts 
from #temp_scoring ts
where exists (
 select 1
 from #temp_edu te
 where te.ID = ts.ID  
 and te.acct_num = ts.acct_num
)