工作样本
示例表:
create table products (productid int primary key)
insert products select 1
insert products select 2
GO
create table ProductSupportArticles (
ProductSupportArticleID int NOT NULL primary key,
ParentArticleID int NULL references ProductSupportArticles(ProductSupportArticleID),
ProductID int NOT NULL references products (productid),
Title varchar(100) NOT NULL,
Content varchar(MAX) NOT NULL
)
GO
支持功能
create function dbo.getProductSupportArticleParent(@ParentArticleID int)
returns int
with returns null on null input
as
begin
return (select ProductID from ProductSupportArticles where ProductSupportArticleID = @ParentArticleID)
end
GO
约束
alter table ProductSupportArticles add check(
ParentArticleID is null or
dbo.getProductSupportArticleParent(ParentArticleID) = ProductID)
GO
测试
insert ProductSupportArticles select 1,null,1,3,4
insert ProductSupportArticles select 2,null,1,3,4
insert ProductSupportArticles select 3,null,2,3,4
insert ProductSupportArticles select 4,1,1,3,4
好的,到目前为止,下一个打破了它,因为 5 是 1 的父级,它属于产品 1。
insert ProductSupportArticles select 5,1,2,3,4
编辑
亚历克斯指出了一个有效的缺陷。为了涵盖这种情况,您需要一个 UPDATE 触发器,它将对记录的 ProductID 的更改传播到所有子(和后代)记录。这将是一个简单的触发器,所以我不会在这里提供代码。