SQL Server DELETE和WITH子句

ala*_*ala 7 sql-server

我需要构建一个SQL语句来从某个表中删除与另一个select语句匹配的记录.

在Teradata我们使用

delete from table1 
where (col1, col2) in (
  select col1,col2
  from table2
)
Run Code Online (Sandbox Code Playgroud)

在SQL Server中,不允许在WHERE..IN子句中包含多于一列的列.我以为我可以使用WITH子句:

with tempTable(col1,col2) as (
select col1,col2
from table2
)
delete from table1
where table1.col1 = tempTable.col1
and table1.col2 = tempTable.col2
Run Code Online (Sandbox Code Playgroud)

如何使用WITH..DELETE子句?还有另外一种方法吗?

Phi*_*ley 20

这应该这样做:

DELETE Table1
 from Table1 t1
  inner join tempTable t2
   on t2.Col1 = t1.Col1
    and t2.Col2 = t1.Col2
Run Code Online (Sandbox Code Playgroud)


Joe*_*orn 5

首先构建一个查询来选择您需要的行:

SELECT t1.*
FROM [Table1] t1
INNER JOIN [Table2] t2 ON t1.[col1] = t2.[col1] AND t1.[Col2]=t2.[Col2]
Run Code Online (Sandbox Code Playgroud)

测试它以确保它准确地返回您要删除的行。然后将“SELECT”更改为“DELETE”并删除列列表,将其变成删除语句:

DELETE t1
FROM [Table1] t1
INNER JOIN [Table2] t2 ON t1.[col1] = t2.[col1] AND t1.[Col
Run Code Online (Sandbox Code Playgroud)