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

时间:2012-05-04 06:31:34

标签: sql-server triggers

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

3 个答案:

答案 0 :(得分:32)

在这种情况下,你可能最好做一个常规的“后”触发器。这是解决此类情况的最常见方法。

这样的东西
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表是包含记录的虚拟表( s)因为它们是在删除之前。

另请注意,触发器在delete语句中作为隐式事务的一部分运行,因此如果删除失败并回滚,则触发器也将回滚。

答案 1 :(得分:13)

您也可以使用INSTEAD OF DELETE

CREATE TRIGGER dbo.SomeTableYouWhatToDeleteFrom
ON dbo.YourTable
INSTEAD OF DELETE
AS
BEGIN

     -- Some code you want to do before delete

     DELETE YourTable
     FROM DELETED D
     INNER JOIN dbo.YourTable T ON T.PK_1 = D.PK_1
END

答案 2 :(得分:1)

可以按照以下步骤完成,我想在这个例子中我使用的是客户表:

CREATE TABLE CUSTOMERS(
   ID   INT              NOT NULL,
   NAME VARCHAR (20)     NOT NULL,
   AGE  INT              NOT NULL,
   ADDRESS  CHAR (25) ,
   LAST_UPDATED DATETIME,
   PRIMARY KEY (ID)
);
  1. 创建历史记录:

    CREATE TABLE CUSTOMERS_HIST( 
    ID   INT              NOT NULL,
    NAME VARCHAR (20)     NOT NULL,
    AGE  INT              NOT NULL,
    ADDRESS  CHAR (25) ,
    LAST_UPDATED DATETIME,
    PRIMARY KEY (ID)
    );
    
  2. 在删除事件上触发源表(如下所示):

    CREATE TRIGGER TRG_CUSTOMERS_DEL 
    ON CUSTOMERS
    FOR DELETE
    AS
         INSERT INTO CUSTOMERS_HIST (ID, NAME, AGE, ADDRESS, LAST_UPDATED)
         SELECT ID, NAME, AGE, ADDRESS, LAST_UPDATED
         FROM DELETED