How to create a before delete trigger in 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_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.
另外,请注意触发器作为删除语句上的隐式事务的一部分运行,因此如果您的删除失败并回滚,触发器也会回滚.
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 中创建删除前触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 SQL Server 中创建删除前触发器?


基础教程推荐
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01