【发布时间】:2021-04-21 23:52:20
【问题描述】:
我想删除一个包含博客评论和博客评论回复的用户(父表)
我将其编码为首先删除 BlogCommentReply(BlogComment 的子项),然后是 BlogComment(BlogCommentReply 的父项),然后是用户(两者的父项)。
我得到错误:
DELETE 语句与 REFERENCE 约束“FK_BlogCommentReply_UserId”冲突。冲突发生在数据库“DBGbngDev”、表“dbo.BlogCommentReply”、列“UserId”中。
我在 BlogCommentReply 和 BlogComment 表上有 FK 键。
1.) 我是否正确创建了表结构?
2.) 我需要级联 - 为什么?
3.) 删除代码顺序是否正确?
_ 我相信直到
首先删除孩子。对吗?
表创建:
CREATE TABLE [dbo].[User]
(
[UserId] [int] IDENTITY(1,1) NOT NULL, -- PK
other columns....
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[UserId] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS =
ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[BlogComment]
(
[BlogCommentId] [int] IDENTITY(1,1) NOT NULL, -- PK
[UserId] [int] NOT NULL, -- FK
other columns....
CONSTRAINT [PK_BlogComment] PRIMARY KEY CLUSTERED
(
[BlogCommentId] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[BlogComment] WITH CHECK ADD CONSTRAINT [FK_BlogComment_UserId] FOREIGN
KEY([UserId]) REFERENCES [dbo].[User] ([UserId])
GO
CREATE TABLE [dbo].[BlogCommentReply]
(
[BlogCommentReplyId] [int] IDENTITY(1,1) NOT NULL, -- PK
[UserId] [int] NOT NULL, -- FK
[BlogCommentId] [int] NOT NULL, -- FK
other columns....
CONSTRAINT [PK_BlogCommentReply] PRIMARY KEY CLUSTERED
(
[BlogCommentReplyId] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS =
ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[BlogCommentReply] WITH CHECK ADD CONSTRAINT [FK_BlogCommentReply_UserId] FOREIGN
KEY([UserId]) REFERENCES [dbo].[User] ([UserId])
GO
ALTER TABLE [dbo].[BlogCommentReply] WITH CHECK ADD CONSTRAINT [FK_BlogCommentReply_BlogCommentId]
FOREIGN KEY([BlogCommentId]) REFERENCES [dbo].[BlogComment] ([BlogCommentId])
GO
执行删除的存储过程(为讨论而简化):
DELETE dbo.BlogCommentReply
FROM dbo.BlogComment a
WHERE ( BlogCommentReply.BlogCommentId = a.BlogCommentId AND BlogCommentReply.UserId = @a_UserId )
DELETE dbo.BlogComment
WHERE UserId = @a_UserId
DELETE dbo.[User]
WHERE ( UserId = @a_UserId )
【问题讨论】:
标签: sql-server