SQL Server - after insert trigger - update another column in the same table

后端 未结 7 842
一向
一向 2020-12-04 22:27

I\'ve got this database trigger:

CREATE TRIGGER setDescToUpper
ON part_numbers
 AFTER INSERT,UPDATE
AS
DECLARE @PnumPkid int, @PDesc nvarchar(128)

SET @Pnum         


        
7条回答
  •  情书的邮戳
    2020-12-04 23:02

    Another option would be to enclose the update statement in an IF statement and call TRIGGER_NESTLEVEL() to restrict the update being run a second time.

    CREATE TRIGGER Table_A_Update ON Table_A AFTER UPDATE 
    AS
    IF ((SELECT TRIGGER_NESTLEVEL()) < 2)
    BEGIN
        UPDATE a
        SET Date_Column = GETDATE()
        FROM Table_A a
        JOIN inserted i ON a.ID = i.ID
    END
    

    When the trigger initially runs the TRIGGER_NESTLEVEL is set to 1 so the update statement will be executed. That update statement will in turn fire that same trigger except this time the TRIGGER_NESTLEVEL is set to 2 and the update statement will not be executed.

    You could also check the TRIGGER_NESTLEVEL first and if its greater than 1 then call RETURN to exit out of the trigger.

    IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;
    

提交回复
热议问题