2017-10-17 3 views
0

の外部キーを持つ複数のテーブルからレコードを削除し、私は3つのテーブルがあります。テーブル間は、SQL Serverの

  • ポスト
  • のようにコメント

関係を、次のとおりです。

  • ポストテーブル:postid PK
  • 表のように0
  • :LikeID PK、CommentID FK
  • 、コメントテーブルのFKをpostid:CommentID PK、PostID 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'で発生しました。

メッセージレベル547、レベル16、状態0、行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'からself-join deleteを実行してみてください。後者のエラーが消えるかもしれないと思います。あるいは、 'userid'が何か違う' postid'のレコードをlikesテーブルに持っている可能性があります。 – pimbrouwers