我有一张带有相关照片表的产品表,可以保存每周广告的产品,例如每年52套产品。我有一个单独的产品和照片库记录区域,使用触发器更新/插入,使库保持最新的产品/图像保存。
插入/更新效果很好。
我希望在删除产品图片时删除库图像,但仅当它不是因为产品级联删除时才会删除(如果他们删除了产品,我仍然希望将产品保留在库中。如果他们删除了一张单独的照片,我想从图书馆中删除该单张照片)
如何在照片表触发器中知道删除是否是级联的结果?我在插入/更新/删除后尝试检查缺失的产品记录,但就触发器而言,这些记录仍然存在。
create table product (
id int not null -- primary key
)
create table productimage (
id int not null -- primary key
, parentid int not null -- foreign key to product id
)
alter trigger dbo.UpdateProductImageLibrary
on dbo.productimage
after update, insert as
begin
declare @insertedcount int, @deletedcount int
select @deletedCount = count(*) from deleted
select @insertedCount = count(*) from inserted
declare @isInsert bit, @isUpdate bit, @isDelete bit
if( @deletedCount = 0 and @insertedCount > 0)
begin
set @isInsert = 1; set @isUpdate = 0; set @isDelete = 0
end
if( @deletedCount > 0 and @insertedCount = 0)
begin
set @isInsert = 0; set @isUpdate = 0; set @isDelete = 1
end
if( @deletedCount > 0 and @insertedCount > 0)
begin
set @isInsert = 0; set @isUpdate = 1; set @isDelete = 0
end
-- At this point we know if product image is an insert, update or delete
-- but the parent table's records are still there if we
-- check for them, even during a cascading delete
end