使用SQL Server中的外键从多个表中删除记录

时间:2017-10-17 20:30:45

标签: sql-server database

我有3张桌子:

  • 注释

表之间的关系是:

  • 邮政表:postid PK
  • 喜欢表:LikeID PK,postid FK,CommentID FK
  • 评论表:CommentID PK,PostID FK,CommentReplybyID FK(自我加入纪念)

现在我必须从帖子表中删除帖子,但是我收到了错误。

我在下面使用此查询:

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

我收到这些错误:

  

Msg 547,Level 16,State 0,Line 8
  DELETE语句与SAME TABLE REFERENCE约束" Comments_fk3"冲突。冲突发生在数据库" development-topthat",table" dbo.Comments",column' CommentReplyID'。

     

Msg 547,Level 16,State 0,Line 9
  DELETE语句与REFERENCE约束冲突" Likes_fk1"。冲突发生在数据库" development-topthat",table" dbo.Likes",column' PostID'。

我在做错的地方需要帮助。怎么做到这一点?

1 个答案:

答案 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 =@postid and userid = @userid

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

rollback tran