我正在尝试在SQL Server数据库中进行软删除,我具有以下简单关系:
博客表:
PK BlogId, Name, Deleted
发布表格:
PK PostId, FK BlogId, Title, Deleted
帖子表具有带约束的外键,该约束可确保每个帖子都有一个现有博客,并且在删除博客时应删除所有相关帖子。
但是,如何考虑软删除来建立FK约束,因此,当我将博客记录设置为已删除时,将迫使我将所有相关帖子也标记为已删除。
更新:我发现时态表非常有用,可以代替软删除功能,因为它可以跟踪包括记录删除在内的整个更改历史。(但仍然对在其中进行软删除感兴趣问题)
答案 0 :(得分:2)
您可以在BlogId
和Deleted
字段上创建复合外键,并将ON UPDATE
选项设置为CASCADE
。
CREATE TABLE Blog (
BlogId INT NOT NULL,
[Name] VARCHAR(20) NOT NULL,
Deleted BIT NOT NULL,
CONSTRAINT PK_Blog PRIMARY KEY (BlogId),
CONSTRAINT AK_Blog UNIQUE (BlogId, Deleted)
);
GO
CREATE TABLE Post (
PostId INT NOT NULL,
BlogId INT NOT NULL,
Title VARCHAR(20) NOT NULL,
Deleted BIT NOT NULL,
CONSTRAINT FK_PostBlog FOREIGN KEY (BlogId, Deleted)
REFERENCES Blog (BlogId, Deleted)
ON UPDATE CASCADE
);
GO
INSERT INTO Blog VALUES (1, 'Blog 1', 0);
INSERT INTO Post VALUES (1, 1, 'Post 1', 0);
UPDATE Blog SET Deleted = 1 WHERE BlogId = 1;
-- Notice that the `Deleted` field in `Post` is now '1' and not '0'.
SELECT * FROM Post;