删除触发器以将条目插入表中

时间:2016-05-10 21:07:13

标签: sql sql-server tsql triggers

在我的Customers_Audit数据库中创建了一个DEV_SQL表,其中包含以下列:

[AuditID] int IDENTITY
[CustomerID] nchar(5)
[UserName] nvarchar(50)
[DeleteDate] smalldatetime

我正在尝试编写一个删除触发器,以便每次从Customers_Audit表中删除一行时向Customers表插入一个条目,需要一些帮助哦明智的!

1 个答案:

答案 0 :(得分:1)

您需要这样的内容 - 只需在Customers_Audit触发器中将行插入AFTER DELETE并根据需要设置固定值:

CREATE TRIGGER trgAfterDelete 
ON dbo.Customer
AFTER DELETE
AS 
    -- insert into the audit table - explicitly specifying the column names to use
    INSERT INTO dbo.Customers_Audit(CustomerId, UserName, DeleteDate)
        -- make sure to respect the fact that the "Deleted" table might
        -- contain *multiple* rows if your DELETE statement deleted 
        -- more than a single row - use proper set-based code!
        SELECT
            d.CustomerId, d.UserName, SYSDATETIME()
        FROM 
            Deleted d