而不是删除多行的触发器代码

时间:2015-12-10 09:44:50

标签: sql sql-server triggers foreign-keys sql-delete

以下是我的表格示例:

Parent

当我从Id & type表中删除一行时,还必须从Child表中删除与INSTEAD OF DELETE匹配的对应行。

以下CREATE TRIGGER [InsteadOFDelete] ON [dbo].[Parent] INSTEAD OF DELETE AS BEGIN IF @@ROWCOUNT = 0 RETURN DECLARE @id Int , @type nvarchar(max) Select @id = Id,@type = Type FROM deleted DELETE FROM Child WHERE Child.Id = @id AND Child.Type = @type; //Then delete from the parent table END 触发器可用于从Parent表中删除单行,但在删除多行时会失败。任何人都可以建议一个有效的解决方案。

SwaggerSerializers

1 个答案:

答案 0 :(得分:2)

您可以使用内部联接到deleted表来执行此操作:

delete C
from Child as C
    inner join deleted as D on D.ID = C.ID and D.Type = C.Type

delete P
from Parent as P
    inner join deleted as D on D.ID = P.ID and D.Type = P.Type