自引用外键约束和删除

编程入门 行业动态 更新时间:2024-10-25 00:35:43
本文介绍了自引用外键约束和删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在SQL-Server中处理自引用外键约束的建议方法是什么?

what is the recommended way to handle self-referencing foreignkey constraints in SQL-Server?

表模型:

code> fiData 引用tabData中的上一条记录。如果我删除由 fiData 引用的记录,数据库会引发一个异常:DELETE语句与SAME TABLE REFERENCE约束FK_tabDataPrev_tabDataNext 。冲突发生在数据库MyDataBase,表dbo.tabData,列'fiData'如果 Enforce Foreignkey Constraint 设置为是的。

fiData references a previous record in tabData. If i delete a record that is referenced by fiData, the database throws an exception: "The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "FK_tabDataPrev_tabDataNext". The conflict occurred in database "MyDataBase", table "dbo.tabData", column 'fiData'" if Enforce Foreignkey Constraint is set to "Yes".

我不需要级联删除被引用的记录,但我需要设置 fiData = NULL 引用它。我的想法是将强制外键约束设置为否并创建一个删除触发器。这是可推荐的还是有更好的方法?

I don't need to cascade delete records that are referenced but i would need to set fiData=NULL where it's referenced. My idea is to set Enforce Foreignkey Constraint to "No" and create a delete-trigger. Is this recommendable or are there better ways?

谢谢。

推荐答案

p>不像Andomar,我会很高兴使用触发器 - 但我不会删除约束检查。如果将其实现为而不是触发器,则可以在执行实际删除之前将其他行重置为null:

Unlike Andomar, I'd be happy using a trigger - but I wouldn't remove the constraint checking. If you implement it as an instead of trigger, you can reset the other rows to null before performing the actual delete:

CREATE TRIGGER T_tabData_D on tabData instead of delete as set nocount on update tabData set fiData = null where fiData in (select idData from deleted) delete from tabData where idData in (select idData from deleted)

简短,简洁,如果SQL Server可以处理外键关联到同一个表(在其他RDBMS',你可以只是指定 ON DELETE SET NULL 用于外键约束YMMV)。

It's short, it's succinct, it wouldn't be necessary if SQL Server could handle foreign key cascades to the same table (in other RDBMS', you may be able to just specify ON DELETE SET NULL for the foreign key constraint, YMMV).

更多推荐

自引用外键约束和删除

本文发布于:2023-10-14 21:48:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492310.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!