如何在检查约束中引用其他表?
我有一个表,ProductSupportArticles:
ProductSupportArticleID int NOT NULL <primary key>
ParentArticleID int NULL
ProductID int NOT NULL
Title varchar(100) NOT NULL
Content varchar(MAX) NOT NULL
ProductID是Products.ID的外键,ParentArticleID是同一个表ProductSupportArticles.ProductSupportArticleID的外键。我有一个检查约束 ProductSupportArticleID != ParentArticleID ,以便文章不能成为其自己的父项。
但是,与特定产品相关的支持文章不应成为与不同产品相关的文章的父项或子项。如何添加检查约束或类似的说法: (ProductID = (SELECT ProductID FROM ProductSupportArticles P WHERE ParentArticleID = P.ProductSupportArticleID))
或者我应该如何以不同的方式实现我的表?
I have a table, ProductSupportArticles:
ProductSupportArticleID int NOT NULL <primary key>
ParentArticleID int NULL
ProductID int NOT NULL
Title varchar(100) NOT NULL
Content varchar(MAX) NOT NULL
ProductID is a foreign key to Products.ID, ParentArticleID is a foreign key to the same table, ProductSupportArticles.ProductSupportArticleID. I have a check constraint ProductSupportArticleID != ParentArticleID so that an article cannot be its own parent.
However, a support article pertaining to a particular product should not be able to be the parent or child of an article pertaining to a different product. How can I add a check constraint or similar saying: (ProductID = (SELECT ProductID FROM ProductSupportArticles P WHERE ParentArticleID = P.ProductSupportArticleID))
Or how should I implement my tables differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
警告:通过 CHECK 约束中包含的 UDF 强制执行业务规则存在多个漏洞。例如,它们可能会针对多行修改给出误报和漏报。而且它们的速度也很慢。
Warning: enforcing business rules via UDFs wrapped in CHECK constraints has multiple loopholes. For example, they may give false positives and false negatives for multi-row modifications. Also they are very slow.
工作示例
示例表:
支持函数
约束
测试
到目前为止,下一个会破坏它,因为 5 的父级是 1,而 1 属于产品 1。
编辑
亚历克斯指出了一个有效的缺陷。为了涵盖这种情况,您需要一个 UPDATE 触发器,将对记录的 ProductID 的更改传播到所有子(和后代)记录。这将是一个简单的触发器,因此我不会在此处提供代码。
Working sample
Sample tables:
Support function
The constraint
Tests
Ok so far, this next one breaks it because 5 is parented by 1, which belongs to product 1.
EDIT
Alex has pointed out a valid flaw. To cover that scenario, you would need an UPDATE trigger that will propagate changes to a record's ProductID to all child (and descendant) records. This would be a simple trigger, so I won't provide the code here.