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

How to create a before delete trigger in SQL Server?(如何在 SQL Server 中创建删除前触发器?)
本文介绍了如何在 SQL Server 中创建删除前触发器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个删除前触发器.当我从表中删除一条记录时,该记录必须插入到历史表中.如何在 SQL Server 中执行此操作?

I want to create a before delete trigger. When I delete a record from a table that record has to be inserted into a history table. How can I do this in SQL Server?

推荐答案

在这种情况下,您可能最好执行常规的after"触发器.这是处理此类情况的最常见方法.

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_tableDELETED 表是一个虚拟的包含删除前的记录的表.

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.

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

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.

这篇关于如何在 SQL Server 中创建删除前触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)