如何设置基于触发器的审核?

时间:2020-07-06 03:51:57

标签: sql sql-server tsql ssms ssms-2012

我有一张桌子Employee

CREATE TABLE [dbo].[Employee]
(
    [EmployeeCode] [int] NOT NULL,
    [FirstName] [varchar](50) NULL,
    [LastName] [varchar](50) NULL,
    [Email] [varchar](50) NULL,
    [Position] [varchar](30) NULL
)

每次{中的Employee_Audit(以及PositionOld PositionNew Position)中有变化时,我都想在Timestamp表中记录更改{1}}表。

Employee

我该如何实现?

2 个答案:

答案 0 :(得分:2)

您基本上需要一个UPDATE触发器来检查Position值是否已更改-如果已更改,则将详细信息记录到Employee_Audit中:

CREATE OR REPLACE trgEmployeeUpdate
ON dbo.Employee 
AFTER UPDATE 
AS
BEGIN
    -- based on the Inserted and Deleted pseudo tables, join the rows
    -- that were updated and look for changes in "Position"
    INSERT INTO dbo.Employee_Audit (EmployeeCode, FirstName, LastName, Email, 
                                    PositionOld, PositionNew, [Date])
        SELECT
            i.EmployeeCode, i.FirstName, i.LastName, i.Email,
            d.Position, i.Position, SYSDATETIME()
        FROM
            Inserted i
        INNER JOIN
            Deleted d ON i.EmployeeCode = d.EmployeeCode
        WHERE
            i.Position <> d.Position    -- Position has changed
END

答案 1 :(得分:1)

除了提到的触发器选项@marc_s之外,如果您不只是考虑位置,并考虑所有列更改审核,下面的选项可让您进行审核,而无需任何特定的编程需求。您可以查看它是否适合您的需求。