我試圖創建一個從[t_Supporter]刪除行的觸發器,當從t_user刪除一行並刪除[t_Supporter]行從t_ticket刪除行時。如何創建一個INSTEAD OF DELETE
create trigger [dbo].[deleteUser]
on [dbo].[t_user]
INSTEAD OF DELETE
as
BEGIN
delete from [dbo].[t_Supporter]
where EXISTS (SELECT 1
FROM deleted
WHERE deleted.userID = [t_Supporter].userID_FK )
DELETE FROM [dbo].[t_user]
where EXISTS (SELECT 1
FROM deleted
WHERE deleted.userID = [t_user].userID )
END
create TRIGGER [dbo].[supporterDelete]
ON [dbo].[t_Supporter]
INSTEAD OF DELETE
AS
BEGIN
update t_ticket
set supporterID_FK = null,supDelete = 1
where EXISTS (SELECT 1
FROM deleted
WHERE deleted.userID_FK = t_ticket.supporterID_FK)
DELETE FROM [dbo].[t_Supporter]
where EXISTS (SELECT 1
FROM deleted
WHERE deleted.supporterID = [t_Supporter].supporterID )
END
,但是當我從T_USER刪除,我得到這個錯誤:
如果你的刪除過程真的需要這樣的觸發,我寧願使用一個存儲過程「DeleteUser」,在這個過程中你一口氣做了棘手的工作。爲了確保這種方法,您可以使用而不是觸發器來避免錯誤的刪除。您的SP會在開始時禁用這些觸發器,並將其作爲最後一個操作。 – Shnugo
我想它,而不是deleted.userID = [t_Supporter] .userID_FK,我使用deleted.supporterID = t_ticket.supporterID_FK –
還有一件事要考慮:實際上應該刪除數據的情況確實很少。更好地標記爲「已刪除」。通過這種方式,你可以在誰的旁邊寫下什麼時候刪除這個。你可以在更大的periodes中存檔例程(物理清理)。 – Shnugo