2017-10-17 43 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