2017-10-17 42 views
0

我有3個表:刪除記錄在SQL Server上的外鍵

  • 像表之間
  • 評論

關係是:

  • 郵寄表格:postid PK
  • 如表:LikeID PK,帖子ID FK,CommentID FK
  • 評語表:CommentID PK,帖子ID FK,CommentReplybyID FK(自連接上commentid)

現在我要刪除帖子表,但我交我得到一個錯誤。

我使用下面這個查詢:

begin tran 

declare @userid int = 68; 
declare @postid int = 15; 

delete from likes 
where postid = @postid and userid = @userid 

delete from comments 
where postid = @postid and userid = @userid 

delete from post 
where postid = @postid and userid = @userid 

rollback tran 

我得到這些錯誤:

消息547,級別16,狀態0,第8行
DELETE語句衝突以相同的表REFERENCE約束「Comments_fk3」。衝突發生在數據庫「development-topthat」,表「dbo.Comments」,列'CommentReplyID'。

Msg 547,Level 16,State 0,Line 9
DELETE語句與REFERENCE約束「Likes_fk1」衝突。衝突發生在數據庫「development-topthat」,表「dbo.Likes」,列'PostID'。

我需要幫助,我在哪裏做錯了。如何實現這一目標?

+0

您有必須處理的外鍵約束。 – ivan7707

+0

是的,我知道,但如何? –

回答

0

通過CommentReplyID的外觀和自我連接評論我懷疑你在評論表中有某種嵌套關係。

您需要刪除CommentReplyId與刪除註釋相匹配的記錄。

begin tran 

declare @userid int = 68; 
declare @postid int = 15; 

-- are you sure userid should be used here? 
delete from likes where postid = @postid and userid = @userid 

delete from comments c1 join comments c2 on c2.CommentReplyId = c1.CommentId where c1.postid = @postid and c1.userid = @userid 

delete from comments where postid [email protected] and userid = @userid 

delete from post where postid = @postid and userid = @userid 

rollback tran 
+0

關於表格上的postID錯誤呢? –

+0

嘗試首先從'comment'執行自聯接刪除,我想後面的錯誤可能會消失。或者,我懷疑你可能在喜歡的表中有記錄,那個'用戶標識符'是不同的。 – pimbrouwers