且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SQL Server的触发器中编辑INSERT的值?

更新时间:2022-12-04 13:36:58

使用插入后触发器。从插入的伪表连接到主键上的 Tb 。然后更新desc的值。诸如此类:(但可能无法编译)

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

此触发器在插入发生后但在 insert 语句完成。因此,新的,错误的值已放置在目标表中。

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.

注意,在触发after触发器之前,将强制执行完整性约束。因此,您不能设置检查约束来强制使用DESC的正确形式。因为这将导致语句在触发器有机会修复任何内容之前失败。 (请先仔细检查此段,然后再依赖它。自编写触发器以来已经有一段时间了。)

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.)