views:

2393

answers:

3

I need to build an SQL statement to delete from certain table the records that match another select statement.

In Teradata we use

delete from table1 
where (col1, col2) in (
  select col1,col2
  from table2
)

While in SQL Server it's not allowed to have more than 1 column in the WHERE..IN clause. I thought I can use the WITH clause:

with tempTable(col1,col2) as (
select col1,col2
from table2
)
delete from table1
where table1.col1 = tempTable.col1
and table1.col2 = tempTable.col2

How to use WITH..DELETE clause? Is there another way?

+5  A: 

This should do it:

DELETE Table1
 from Table1 t1
  inner join tempTable t2
   on t2.Col1 = t1.Col1
    and t2.Col2 = t1.Col2
Philip Kelley
...you could use the WITH clause, but this way is simpler.
Philip Kelley
thanks it worked! but how to use WITH..DELETE?
ala
Thinking about it, I see no reason to use the WITH clause. I use WITH when things get seriously messy or complex, and deleting from a table based on a simple join to another table isn't complex enough to warrant the extra coding effort.
Philip Kelley
I agree that creating a CTE (WITH) isn't really warranted, but as to how--it's right there. The join in the answer is to the CTE (note the name...).
RolandTumble
+1  A: 
delete from table1 t1 where exists 
  ( 

   select 1 from table2 t2 where t1.col1 = t2.col1 and t1.col2 > t2.col2

)
phatmanace
This syntax is incorrect
Philippe Leybaert
The syntax is incorrect, but the general idea is correct. SQL Server can optimize this so it should perform as well as a solution using a join while being easier to read IMO.
EvilRyry
+1  A: 

First build a query that selects the rows you need:

SELECT t1.*
FROM [Table1] t1
INNER JOIN [Table2] t2 ON t1.[col1] = t2.[col1] AND t1.[Col2]=t2.[Col2]

Test it to make sure it returns exactly the rows you want to delete. Then turn it into a delete statement by changing the "SELECT" to "DELETE" and removing the column list:

DELETE t1
FROM [Table1] t1
INNER JOIN [Table2] t2 ON t1.[col1] = t2.[col1] AND t1.[Col
Joel Coehoorn
That's good advice in SSMS, but not very practical programmaticly....
RolandTumble