且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自引用外键约束和删除

更新时间:2022-06-04 08:48:55

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).