从多个相关表中删除

时间:2012-09-06 19:17:01

标签: sql sql-server-2008

我是SQL Server的新手,我还在学习一些交易技巧,而另一个教我的人本周都没有工作,通常我会首先运行他的声明然后跑吧。

我要做的是删除此select语句中返回的所有内容:

SELECT * from LOCATIONS a Join CONTACTS b on a.location_ID = b.Location_ID 
join CONTACTS_SOURCES c on b.contact_ID = c.Contact_ID  where c.Source_ID = 10014918

我需要删除此语句从CONTACTS表和LOCATIONS表中返回的内容。这样做的最佳途径是哪条路线?

路线A:

delete from LOCATIONS a
Join CONTACTS b
on a.location_ID = b.Location_ID
join CONTACTS_SOURCES c
on b.contact_ID = c.Contact_ID  where c.Source_ID = 10014918

或路线B.

DELETE from LOCATIONS where (SELECT * from LOCATIONS a
Join CONTACTS b
on a.location_ID = b.Location_ID
join CONTACTS_SOURCES c
on b.contact_ID = c.Contact_ID  where c.Source_ID = 10014918)

DELETE FROM CONTACTS where (SELECT * from LOCATIONS a
Join CONTACTS b
on a.location_ID = b.Location_ID
join CONTACTS_SOURCES c
on b.contact_ID = c.Contact_ID  where c.Source_ID = 10014918)

我感觉路线A.不会从LOCATIONS和CONTACTS表中删除。

2 个答案:

答案 0 :(得分:7)

您的感觉是正确的:DELETE查询(实际上是任何DML查询)只能影响单个表。路由B的问题是第二个查询无效,因为第一个查询删除了所有可能成为连接候选的行。

怎么样:

SELECT l.Location_ID, c.Contact_ID
  INTO #x
  FROM dbo.LOCATIONS AS l
  INNER JOIN dbo.CONTACTS AS c
  ON l.location_ID = c.Location_ID
  INNER JOIN dbo.CONTACTS_SOURCES AS cs
  ON c.contact_ID = cs.Contact_ID 
  WHERE cs.Source_ID = 10014918;

DELETE dbo.CONTACTS_SOURCES WHERE Contact_ID IN (SELECT Contact_ID FROM #x);

DELETE dbo.CONTACTS WHERE Contact_ID IN (SELECT Contact_ID FROM #x);

DELETE dbo.LOCATIONS WHERE Location_ID IN (SELECT Location_ID FROM #x);     

答案 1 :(得分:1)

如果您在所有3个表(联系人,位置和联系人来源)上都具有参照完整性,那么您需要按顺序从leaf删除到父级:

  1. Contact_sources
  2. 联系人
  3. 位置