2016-07-06 47 views
1

我想弄清楚一种方法来创建一个循环,将从不同的表的列中获取一个id并使用该id来执行删除操作。创建循环使用来自另一个表中的值来执行删除

@ID表示与另一个表的不同ID。我如何创建一个循环来读取每个ID并删除基于该ID的其他表中的行?

Declare @ID int 
Set @ID = dbo.control.id 

Delete from dbo.search where [email protected] 
Delete from dbo.searchfolder where [email protected] 
Delete from dbo.application where id [email protected] 
+1

除非循环中有其他逻辑,否则不需要其他逻辑。只需在你的'delete'语句中使用'join'。 – sgeddes

+0

id会有所不同。 – Jeff

回答

3

你不需要一个循环,刚刚加入将工作,可以实现相同的逻辑

Delete s 
from dbo.search s 
join 
dbo.content c 
on c.id=s.id 

您还可以使用存在的所有表,这可能是在某些情况下更快取决于数据密度

delete from t2 where exists(select 1 from dbo.t1 where t1.id=t2.id) 
+0

你能告诉我一个存在的样本吗? – Jeff

+0

我在回答示例代码时注意到了 – TheGameiswar

相关问题