sql-server - 两个外键引用一个表-ON UPDATE SET NULL不起作用

标签 sql-server tsql foreign-keys constraints cascade

我在 table 上有两个外键。假设表名为News,并且具有外键updatedByIdcreatedById,它们都指向表userId中的Users

现在,我想在删除用户时设置为NULL外键,但是当我尝试在该关系中设置ON DELETE SET NULL时,我得到:

Introducing FOREIGN KEY constraint 'FK_News_Users' on table 'News' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.



我不明白为什么两个外键都不能设置为null?

最佳答案

Multiple Cascading Actions

The series of cascading referential actions triggered by a single DELETE or UPDATE must form a tree that contains no circular references. No table can appear more than one time in the list of all cascading referential actions that result from the DELETE or UPDATE. Also, the tree of cascading referential actions must not have more than one path to any specified table. Any branch of the tree is ended when it encounters a table for which NO ACTION has been specified or is the default.



在这种情况下,您可能需要考虑实现从逻辑上而不是物理上删除用户的功能(例如,通过在Users表中引入“事件”或“已删除”标志字段)。这样,所有关系都会保持不变,并且可以进行追溯分析。

但是,如果仍然需要为两个FK都实现ON DELETE SET NULL,则可以在FOR DELETE表上使用User触发器,如下所示:

CREATE TRIGGER Users_News_Delete_Trigger 
ON Users FOR DELETE
AS BEGIN
    UPDATE News SET createdById = NULL 
     WHERE createdById = DELETED.id;
    UPDATE News SET updatedById = NULL 
     WHERE updatedById = DELETED.id;
END

关于sql-server - 两个外键引用一个表-ON UPDATE SET NULL不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14553188/

相关文章:

SQL 2005 sp_GetAppLock --- 何时调用 sp_ReleaseAppLock?

sql - 在 varchar 变量 SQL Server 2008 中存储单引号

sql - 查找上周日

sql-server - MS sql 案例语句

c# - EntityFramework : 1:0. .1 关系反序列化为集合

sql - 在 SQL Server 中一次性获取 DISTINCT COUNT

sql - 在T-SQL中强制转换nvarchar变量

sql - 消息传递功能 创建 Sql 查询和数据库 View

MySQL:如何插入具有链接到其他两个表的两个外键的表?

sql - 在 MS SQL Server 中的多个表之间共享基于相同列的复合外键