How can I edit values of an INSERT in a trigger on SQL Server?

后端 未结 5 1831
猫巷女王i
猫巷女王i 2020-12-10 10:05

I have the table Tb

ID | Name   | Desc
-------------------------
 1 | Sample | sample desc

I want to create a trigger on INSER

5条回答
  •  抹茶落季
    2020-12-10 10:44

    Use an after insert trigger. Join from the inserted pseudo table to Tb on the primary key. Then update the values of desc. Something like: (But may not compile)

    CREATE TRIGGER TbFixTb_Trg 
    ON  Tb  
    AFTER INSERT 
    AS  
    BEGIN 
        UPDATE Tb
        SET DESC = SomeTransformationOf(i.DESC)
        FROM Tb
        INNER JOIN inserted i on i.Id = Tb.Id
    END  
    GO
    

    This trigger happens after the insert has happened, but before insert statement completes. So the new, incorrect values are already placed in the target table. This trigger will not need to change as columns are added, deleted, etc.

    Caveat Integrity constraints are enforced before the after trigger fires. So you can't put on a check constraint to enforce the proper form of DESC. Because that would cause the statement to fail prior to the trigger having a chance to fix anything. (Please double check this paragraph before relying on it. It's been awhile since I've written a trigger.)

提交回复
热议问题