我有表名称被称为小部件,并且有删除触发器。当我删除一个特定的行时,我想要删除其他具有重新签名的行
触发器
ALTER TRIGGER [dbo].[Trigger_sys_widgets_Delete]
ON [dbo].[sys_widgets]
AFTER DELETE
AS
BEGIN
Delete From sys_Widgets Where parent in (Select id From deleted);
END
但是这不会删除其他行只删除第一行!
我可以在Depete循环中使此触发器工作,直到相对Childs中没有任何内容
还尝试级联删除
Alter Table sys_widgets Add Constraint FK_sys_widgets foreign Key (parent) References sys_widgets(id) On Delete Cascade;
这可能是为同一个表做的吗
答案 0 :(得分:0)
您可以使用递归CTE通过一次触发运行删除所有子项。
ALTER TRIGGER [dbo].[Trigger_sys_widgets_Delete]
ON [dbo].[sys_widgets]
AFTER DELETE
AS
BEGIN
WITH ForDelete AS
(
SELECT widgets.id
FROM [dbo].[sys_widgets] AS widgets
INNER JOIN deleted ON widgets.parent = deleted.id
UNION ALL
SELECT widgets.id
FROM [dbo].[sys_widgets] AS widgets
INNER JOIN ForDelete ON widgets.parent = ForDelete.id
)
DELETE FROM [dbo].[sys_widgets]
WHERE id in (SELECT id FROM ForDelete);
END