Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server SQL Server触发器:如何知道父表记录何时删除_Sql Server_Triggers - Fatal编程技术网

Sql server SQL Server触发器:如何知道父表记录何时删除

Sql server SQL Server触发器:如何知道父表记录何时删除,sql-server,triggers,Sql Server,Triggers,我有一个产品表,其中包含一个相依的照片表,该表每周都会发布产品广告,例如,一年52套产品。我有一个单独的产品和照片库记录区域,它使用触发器更新/插入,使库从上次产品/图像保存时保持最新 插入/更新工作正常 我想在删除产品映像时删除库映像,但只有当不是因为产品级联删除而删除产品时,我仍然希望将产品保留在库中。另外,如果他们删除了一张单独的照片,我想从库中删除该单独的照片 我如何在photo表触发器中知道删除是否是级联的结果?我尝试在插入/更新/删除后检查丢失的产品记录,但就触发器而言,这些记录仍然

我有一个产品表,其中包含一个相依的照片表,该表每周都会发布产品广告,例如,一年52套产品。我有一个单独的产品和照片库记录区域,它使用触发器更新/插入,使库从上次产品/图像保存时保持最新

插入/更新工作正常

我想在删除产品映像时删除库映像,但只有当不是因为产品级联删除而删除产品时,我仍然希望将产品保留在库中。另外,如果他们删除了一张单独的照片,我想从库中删除该单独的照片

我如何在photo表触发器中知道删除是否是级联的结果?我尝试在插入/更新/删除后检查丢失的产品记录,但就触发器而言,这些记录仍然存在

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

我认为,使用级联删除通常不是一个好的做法,尤其是如果您需要围绕它们的特定功能的话。但是,如果为父表设置了FK,则无法删除产品并保留映像,sata完整性规则将不允许也不应允许,如果在父选项卡中删除了parentID,parentID意味着什么。也许这个系统最好在设置了非活动标志的情况下进行软删除,这样用户就看不到产品了,但实际上它并没有被删除。或者,您可以将PK FK反转。如果要在删除产品时保留产品图像表,则听起来好像产品图像表真的是父级。。也许产品表应该将FK改为图像表。@HLGEM我喜欢软删除的想法。不过,逆转FK是不可能的。可以完全删除每周产品,这是预期的,但不应删除镜像库产品。但是,如果它们删除单个映像,则也应删除镜像库的单个映像。我通常会在数据库之外的商业智能层完全处理这个问题。我们有其他应用程序直接在SQL中操作产品,因此我们需要完整性约束。关闭cascades也是一个好主意,但我们仍然需要对外部应用程序进行更改。