且构网

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

如何在SQL Server中创建删除前触发器?

更新时间:2023-02-05 10:21:09

在这种情况下,***执行常规的之后操作触发。这是处理这种情况的最常用方法。

In this situation, you're probably better off doing a regular "after" trigger. This is the most common approach to this type of situation.

类似

CREATE TRIGGER TRG_AUD_DEL
ON yourTable
FOR DELETE
AS
     INSERT INTO my_audit_table  (col1, col2, ...)
     SELECT col1, col2...
     FROM DELETED 

会发生什么,当从表中删除一条记录时,删除的行将插入到 my_audit_table DELETED 表是一个虚拟表,其中包含刚删除前的记录。

What will happen is, when a record (or records!) are deleted from your table, the deleted row will be inserted into my_audit_table The DELETED table is a virtual table that contains the record(s) as they were immediately prior to the delete.

此外,请注意,触发器作为Delete语句上隐式事务的一部分运行,因此,如果删除失败并回滚,则触发器也会回滚。

Also, note that the trigger runs as part of the implicit transaction on the delete statement, so if your delete fails and rolls back, the trigger will also rollback.