使用触发器删除后更新 table

Update table after delete using trigger

如标题所述,当从 Table1 中删除一行时,我正在尝试使用触发器更新 Table2 中的值。我的代码如下所示:

CREATE TRIGGER TRG_Table1_DEL
    ON Table1
    FOR DELETE
AS
    UPDATE Table2 SET
        FK_Table1ID = NULL
    WHERE FK_Table1ID = (SELECT Table1ID FROM DELETED)

总的来说,我只是想模仿一个将列设置为空的约束(ON DELETE SET NULL)。我这样做是因为我收到一条错误消息,提示我在尝试添加约束时可能会导致多个循环或级联路径。

对于我的代码,我基于 this 答案。

这应该适用于 SQL 服务器。我刚刚将 (=) 替换为 (in).

CREATE TRIGGER TRG_Table1_DEL
ON Table1
FOR DELETE
AS
    UPDATE Table2 
    SET FK_Table1ID = NULL 
    WHERE FK_Table1ID IN (SELECT Table1ID FROM DELETED)

示例:

 create table empsalary(empid int, month int , salary int);

 insert into empsalary values(1, 1, 100);
 insert into empsalary values(1, 2, 101);
 insert into empsalary values(1, 3, 103);

 create table emp(empid int, id int);

 insert into emp values(1,1);


CREATE TRIGGER TRG_Table1_DEL
ON empsalary
FOR DELETE
AS
    UPDATE emp 
    SET id = NULL 
    WHERE empid IN (SELECT empid FROM DELETED)
     

 select  * from empsalary
empid month salary
1 1 100
1 2 101
1 3 103
 select  * from emp
empid id
1 1
 delete empsalary where month=1;

 select * from empsalary;
empid month salary
1 2 101
1 3 103
 select  *from emp;
empid id
1 null

db<>fiddle here

原来这个问题有一个非常简单的解决方法。我收到错误是因为我试图在删除约束后添加触发器。这很好,但我忘记在删除约束和创建触发器之间添加一个 GO 命令。我的代码如下所示:

DROP CONSTRAINT
ADD TRIGGER

但这是正确的解决方案:

DROP CONSTRAINT
GO
ADD TRIGGER

编辑:正如DaleK所指出的,我还需要修改 WHERE 子句以防 DELETED table 有多行