在具有两个 FK 到同一个表的表上级联删除

on cascade delete on a table with two FK to the same table(在具有两个 FK 到同一个表的表上级联删除)
本文介绍了在具有两个 FK 到同一个表的表上级联删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Friends 的关系,其中包含以下列,

I have a relation called Friends with the following columns,

User1ID   
User2ID
Since

User1IDUser2ID 是关系中的一组主键.它们也是引用表用户的外键.现在我想添加一个 ON CASCADE DELETE,这样当表 Users 中的用户被删除时,表 Friends 中的相应行也会被删除.但是,MS SQL Server 不允许我添加该约束.

User1ID and User2ID are a set of primary keys in the relation. They are also foreign keys referencing to the table Users. Now i want to add an ON CASCADE DELETE, such that when a user from table Users is deleted then the corresponding row from table Friends is deleted as well. However, MS SQL Server does not allow me to add that constraint.

关于如何修改表格以完成该任务的任何想法?

Any ideas, about how can i modify the table, in order to accomplish that task?

推荐答案

你不能有多个或循环的级联路径:你想做的事情变得模棱两可(比如一个 CASCADE NULL 和另一个 CASCADE DELETE)

You can't have multiple or circular cascade paths: it becomes ambiguous what you want to do (say one CASCADE NULL and the other CASCADE DELETE)

我会使用存储过程首先在事务中从 Friends 中删除,然后从 Users 中删除(当然是在 TRY/CATCH 中处理错误)

I'd use a stored procedure to delete from Friends first in a transaction then from Users (in a TRY/CATCH of course to deal with errors)

BEGIN TRAN
   DELETE Friends WHERE User1ID = @UserID;
   DELETE Friends WHERE User2ID = @UserID;
   DELETE Users WHERE UserID = @UserID;
COMMIT TRAN

这篇关于在具有两个 FK 到同一个表的表上级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
FastAPI + Tortoise ORM + FastAPI Users (Python) - Relationship - Many To Many(FastAPI+Tortoise ORM+FastAPI用户(Python)-关系-多对多)