【问题标题】:Creating SQL constraint with possible circular dependencies使用可能的循环依赖创建 SQL 约束
【发布时间】:2012-07-17 07:38:31
【问题描述】:

我有以下表格结构(虚构的,用于演示):

ArticlePrice
------------
Id (int, identity)
Price (float)

SpecialArticlePrice
-------------------
Id (int, identity)
ArticlePriceId (int, FK to AriclePrice.Id)
SpecialPrice (float)

在这些表之间是一个删除约束。

Foo
-----
Id (int, identity)
ArticlePriceId (int, NULL, FKto ArticlePrice.Id)
SpecialArticlePriceId (int, NULL, FK to SpecialArticlePrice.Id)
Price (int)

我想为两个 FK 设置删除约束,以防 ArticelPrice 或 SpecialArticlePrice 被删除,Foo 记录也应该被删除。 唯一的合同(在开发者网站上)是,Foo 的记录将只包含一个 FK 关系。

例子:

INSERT INTO Foo (ArticlePrice, SpecialArticlePrice, Price) VALUES (13, NULL, 20.0) 
INSERT INTO Foo (ArticlePrice, SpecialArticlePrice, Price) VALUES (NULL, 3, 134.25)

我该如何解决这种情况?

非常感谢。 亲切的问候, 丹尼

【问题讨论】:

  • 我怀疑你有循环依赖。我建议你发布表的 ddl。在这些表中插入一些数据,然后说从 articleprice 表中删除一行并显示你期望其他表的输出.然后从 specialarticleprice 中删除一行,并指定您期望其他两个表的输出。然后人们将能够更快地提供帮助。

标签: sql sql-server constraints circular-dependency


【解决方案1】:

您需要在您的 ArticlePrice 和 SpecialArticlePrice 表上创建 DELETE TRIGGERS

create trigger trgArticlePriceDelete on ArticlePrice for delete
as
begin
delete foo 
from foo
        inner join deleted on foo.ArticlePriceID = deleted.ID
end
go

create trigger trgSpecialArticlePriceDelete on SpecialArticlePrice for delete
as
begin
    delete foo 
    from
        foo
        inner join deleted on foo.SpecialArticlePriceID = deleted.ID
end
go

此外,您不应将价格存储为浮动价格。使用moneydecimal 类型

【讨论】:

  • 不起作用。在执行任何触发操作之前,将检查 FK。解决方案是使用 INSTEAD OF DELETE 类型的触发器。
【解决方案2】:

您可以将触发器与存储过程一起使用。 SQL Server 2008 - Multiple Cascading FK's - Do i need a trigger?

非常感谢, 吉里什

【讨论】:

    【解决方案3】:

    我不知道我是否得到了你真正想要实现的目标但是:

    如果您在 SSMS 中设计 Foo-Table,则必须插入外键。 然后您需要设置 SpecialPrice-Table 和 ArticlePrice-Table 的外键的“插入和更新规范”(与表 Foo 的关系) --> 只需将删除规则设置为 Cascade乙>。

    因此,每次您删除 ArticlePrice 或 SpecialArticlePrice 时,引用这些项目的行也应该被删除。

    【讨论】:

    • 不幸的是,由于循环依赖,不允许设置此规则;)如果我删除 ArticlePrice 记录,该规则将删除 SpecialPrice 记录和 Foo 记录。之后数据库要再次删除 Foo 记录,因为 SpecialArticlePrice 和 Foo 之间存在第二条规则......在我的场景中,不会同时设置两个 FK,但数据库不知道。我猜甲骨文有类似 NOCYCLE 的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多