从单个选择中的多个表中删除

时间:2017-10-23 06:28:34

标签: sql sql-server

我想删除表foo中的记录,但它有许多FK,其他表的参考约束。我没有设置CASCADE 。我可以一个查询吗?类似的东西:

delete f, b
from foo f
left join bar b on b.fooID = f.ID
where f.ID = 11764

1 个答案:

答案 0 :(得分:1)

您需要将查询转换为:

DECLARE @fooId INT = 11764;

DELETE FROM bar 
WHERE fooID = @fooID

DELETE FROM foo
WHERE ID = @fooId

首先声明@fooId变量,如果要删除多个项目,代码更容易重用。

如果你想删除很多项目,根据某些条件,你可以在你放置id的地方声明一个表变量:

DECLARE @deleteItems TABLE
(
    ID INT
);

INSERT INTO @deleteItems (ID)
    SELECT ID FROM foo WHERE <your conditions here>

DELETE FROM Bar 
WHERE FooID in (SELECT ID FROM @deleteItems)

DELETE FROM Foo 
WHERE ID in (SELECT ID FROM @deleteItems)

BEGIN TRANSACTION放在开头并将COMMIT TRANSACTION放在最后也可能是合适的,以确保更新是原子的