Sql server DELETE和WITH子句
问题描述:
我需要构建一条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子句?有另一种方法吗?
答
这应做到:
DELETE Table1
from Table1 t1
inner join tempTable t2
on t2.Col1 = t1.Col1
and t2.Col2 = t1.Col2
答
delete from table1 t1 where exists
(
select 1 from table2 t2 where t1.col1 = t2.col1 and t1.col2 > t2.col2
)
答
首先建立一个选择您需要的行的查询:
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
答
with tempTable(col1,col2) as (
select col1,col2
from table2
)
delete table1 from tempTable
where table1.col1 = tempTable.col1
and table1.col2 = tempTable.col2
答
这对我的作品
WITH CTE AS
(
SELECT TOP 50000 *
from v020101hist order by data
)
DELETE FROM CTE
......你可以使用WITH子句,但这种方法更简单。 – 2009-07-24 13:52:59
感谢它的工作!但如何使用WITH..DELETE? – ala 2009-07-24 14:10:52
想一想,我没有理由使用WITH子句。当事情严重杂乱或复杂时,我使用WITH,并且基于简单连接到另一个表的表格删除不够复杂,不足以保证额外的编码工作。 – 2009-07-24 14:26:03