2009-07-24 113 views
6

我需要構建一條SQL語句,以從某個表中刪除與另一個select語句匹配的記錄。Sql server DELETE和WITH子句

在Teradata數據,我們使用

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

雖然在SQL Server它不允許WHERE..IN子句中有超過1列。我以爲我可以使用WITH子句:

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

如何使用WITH..DELETE子句?有另一種方法嗎?

回答

19

這應做到:

DELETE Table1 
from Table1 t1 
    inner join tempTable t2 
    on t2.Col1 = t1.Col1 
    and t2.Col2 = t1.Col2 
+1

......你可以使用WITH子句,但這種方法更簡單。 – 2009-07-24 13:52:59

+0

感謝它的工作!但如何使用WITH..DELETE? – ala 2009-07-24 14:10:52

+0

想一想,我沒有理由使用WITH子句。當事情嚴重雜亂或複雜時,我使用WITH,並且基於簡單連接到另一個表的表格刪除不夠複雜,不足以保證額外的編碼工作。 – 2009-07-24 14:26:03

1
delete from table1 t1 where exists 
    ( 

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

) 
4

首先建立一個選擇您需要的行的查詢:

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

測試它以確保它正好返回的行你想要刪除。然後,通過改變它變成一個delete語句「選擇」爲「刪除」,刪除列的列表:

DELETE t1 
FROM [Table1] t1 
INNER JOIN [Table2] t2 ON t1.[col1] = t2.[col1] AND t1.[Col 
0
with tempTable(col1,col2) as (
    select col1,col2 
    from table2 
) 
delete table1 from tempTable 
where table1.col1 = tempTable.col1 
and table1.col2 = tempTable.col2 
0

這對我的作品

WITH CTE AS 
(
SELECT TOP 50000 * 
from v020101hist order by data 
) 
DELETE FROM CTE