如何同时从两个表中删除?

时间:2016-06-22 21:18:09

标签: sql ansi-sql

例如,

 DELETE table1., table2. FROM table1, table2 WHERE (((table1.[Field1])=table2.[Field1]));

2 个答案:

答案 0 :(得分:2)

您可以使用删除元素的DELETE CASCADE以及依赖于该元素的任何其他元素。

例如,如果您有一个学生表,一个课程表和一个列出学生想要关注的所有课程的订阅表,您可以使用CASCADE删除学生以及与他相关的任何主菜。

答案 1 :(得分:1)

我建议使用嵌套的CURSOR:

DECLARE @OuterVar [datatype];
DECLARE @OuterPKey [datatype];
DECLARE @InnerPKey [datatype];

DECLARE OuterCursor CURSOR
FOR SELECT table1.[Field1], table1.[PrimaryKey]
FROM table1;

OPEN OuterCursor
FETCH NEXT FROM OuterCursor INTO @OuterVar, @OuterPKey;

WHILE @@FETCH_STATUS = 0
BEGIN

DECLARE InnerCursor CURSOR
FOR SELECT table2.[PrimaryKey]
FROM table2
WHERE table2.[Field2] = @OuterVar;

OPEN InnerCursor;

WHILE @@FETCH_STATUS = 0
BEGIN

DELETE FROM table1 WHERE [PrimaryKey] = @OuterPKey;
DELETE FROM table2 WHERE [PrimaryKey] = @InnerPKey;

FETCH NEXT FROM InnerCursor INTO @InnerPKey;

END;

CLOSE InnerCursor;
DEALLOCATE InnerCursor;

FETCH NEXT FROM OuterCursor INTO @OuterVar, @OuterPKey;

END;

CLOSE OuterCursor;
DEALLOCATE OuterCursor;

这将循环遍历table1中的所有记录,并且对于每个记录,它将在table2中找到table1。[Field1]和table2。[Field2]的值相同的记录。然后它将删除两个记录。