mauzilla
mauzilla

Reputation: 3592

Delete from TableA with Where equals in TableB

I have a staging table through which I want to delete all matching records in my Customers table. In "language terms":

delete 
   tableA.* 
from 
   table A,table B 
where 
    TableA.col1=TableB.col1 
    && TableA.colb=TableB.col2 /// and so forth

Some info about the tables:

I have this working in Linq2SQL but it's taking a longer due to all of the queries and as there is around 80% matching records with each query and I feel a single query should be suffice.

Is this at all possible in SQL?

Upvotes: 0

Views: 44

Answers (2)

Chanukya
Chanukya

Reputation: 5893

merge table1 t1
    using (
        select t2.ID
            from table2 t2
    ) as d
    on t1.ID = d.ID
    when matched then delete;

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use JOIN with DELETE

DELETE a
FROM tableA a
INNER JOIN tableB b
  ON  a.Col1 = b.Col1
  AND a.ColB = b.ColB 
  ... and so on

or by using EXISTS:

DELETE a
FROM tableA a
WHERE EXISTS
(
   SELECT 1 FROM tableB b
   WHERE a.Col1 = b.Col1
     AND a.ColB = b.ColB
     ....
)

Upvotes: 3

Related Questions