2015-09-07 59 views
0

我試圖創建一個從[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刪除,我得到這個錯誤:

enter image description here

+0

如果你的刪除過程真的需要這樣的觸發,我寧願使用一個存儲過程「DeleteUser」,在這個過程中你一口氣做了棘手的工作。爲了確保這種方法,您可以使用而不是觸發器來避免錯誤的刪除。您的SP會在開始時禁用這些觸發器,並將其作爲最後一個操作。 – Shnugo

+0

我想它,而不是deleted.userID = [t_Supporter] .userID_FK,我使用deleted.supporterID = t_ticket.supporterID_FK –

+1

還有一件事要考慮:實際上應該刪除數據的情況確實很少。更好地標記爲「已刪除」。通過這種方式,你可以在誰的旁邊寫下什麼時候刪除這個。你可以在更大的periodes中存檔例程(物理清理)。 – Shnugo

回答

0

你的錯誤明確說法錯誤的原因。

you can't delete a given parent row if a child row exists that references the value for that parent row. If the parent row has no referencing child rows, then you can delete that parent row.this is the default behavior for a foreign key.

你不能從表中刪除記錄,如果你是指它的價值,另一個(Foreign_Key)表,如果參考表有任何值,那麼你會得到刪除錯誤。

因此,您必須先從子表(foreign_key)中刪除記錄,然後才能從主表中刪除記錄。

+0

這不是一個答案......你自己的部分不過是一個(相當明顯)的評論,你的第二部分是我的評論的副本... – Shnugo

+0

可能是,但我已經定義了錯誤的原因。 它會幫助用戶知道爲什麼會出現錯誤。 @Shnugo –

相關問題