简体   繁体   中英

Is it possible to tell in a delete trigger whether it was caused by a cascade delete FK?

I have a trigger that fires on delete in SQL Server 2008 R2. In this trigger, I want to be able to tell the difference between manual deletes from user queries (DELETE FROM...) and deletes caused by the ON DELETE CASCADE action on a foreign key. Is this possible?

The problem I'm trying to solve is that I want to prevent people from deleting from tables directly, but I still want cascade delete foreign keys to work.

Cascading deletes don't check permissions. So just don't grant users the right to delete from the table:

create table T1 (ID int not null primary key)
insert into T1(ID) values (1)
create table T2 (T1ID int not null references T1(ID) on delete cascade)
insert into T2(T1ID) values (1)
go
create user Barry without login
go
grant delete on T1 to Barry
go
deny delete on T2 to Barry
go
execute as user = 'Barry'
go
select USER_NAME()
go
delete from T1
go
revert
go
drop user Barry
go
select * from T2

You can check for existence of row in 'parent' table with appropriate ID. If delete was caused by cascade, there will no longer be the 'parent' row. If there is a parent row, someone is deleting directly in the 'child' table.

SQLFiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM