简体   繁体   中英

Delete intersection between two tables in SQL Server

I wanted to delete the matching accounts (matching on ID and acct_num) from #temp_scoring, but ended up deleting all rows from the table #temp_scoring instead. Here is the code:

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

As a side note, I would have created an alias for #temp_scoring but it was giving me a syntax error when I did that.

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

You can just do a delete with join

Your problem is the column names:

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
)

To be clear, ID = te.ID because that is the ID the nearest enclosing scope.

You probably want this

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM