【问题标题】:How to impose cascade delete or cascade set null on two foreign keys in SQL Server如何对 SQL Server 中的两个外键强制级联删除或级联设置 null
【发布时间】:2018-11-27 23:38:00
【问题描述】:

我有 2 张桌子。

create table A 
(
    idA int primary key,
    .
    .
)

create table B 
(
   idA int, 
   idB int primary key,
   .
   .
   Foreign key (idA) A (idA) ON DELETE CASCADE
)

create Table AB 
(
    idA int,
    idB int,
    .
    .
    Foreign key (idA) A (idA),
    Foreign key (idB) B (idB)
)

应用程序控制数据的方式是,在 表 AB 中,idAidB 中的任何一个都会将另一个设置为 null。

如何强加这样的东西

Foreign key (idA) A (idA) ON DELETE CASCADE,
Foreign key (idB) B (idB) ON DELETE CASCADE,

Foreign key (idA) A (idA) ON DELETE CASCADE,
Foreign key (idB) B (idB) ON DELETE SET NULL,

Foreign key (idA) A (idA) ON DELETE SET NULL,
Foreign key (idB) B (idB) ON DELETE SET NULL,

在每种情况下我都会遇到错误:

SQL 错误 [1785] [S0000]:
在表 'inventory_exception' 上引入 FOREIGN KEY 约束 'FK__inventory_except__2022C2A6' 可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。

【问题讨论】:

  • 您应该在查询之前使用 alter table x
  • 保持外键不做任何操作,使用而不是删除触发器来删除子表中的数据。
  • 为什么两个外键上的 ON DELETE SET NULL 都不起作用。即使我能够在没有触发的情况下做到这一点,我也会很好。
  • @atabrizi 我是直接在create table ddl中给的。

标签: sql sql-server


【解决方案1】:

以下代码有效:

create table A (
    idA int primary key
);

create table B (
   idB int primary key
);

create Table AB (
    idA int,
    idB int,
    check (idA is null and idB is not null or idA is not null and idB is null),
    Foreign key (idA) A (idA) on delete cascade,
    Foreign key (idB) B (idB) on delete cascade
);

Here 是一个 dbfiddle。

您似乎还有其他导致问题的约束。如果是这样,您的问题没有足够的信息来真正解释问题。

【讨论】:

  • 是的,你说得对,它确实有效。我试图简化问题没有检查简化版本是否已经工作。我已经更新了 B 也有 A 的主键作为外键的实际场景。你能在这种情况下提出一些建议吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多