如何设置基于触发器的审计?
How to setup trigger based audit?
我有一个 table 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
)
每当 Position
(以及 Old Position
、New Position
和 Timestamp
) 在 Employee
table.
CREATE TABLE [dbo].[Employee_Audit]
(
[EmployeeCode] [int] NOT NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Email] [varchar](50) NULL,
[PositionOld] [varchar](30) NULL,
[PositionNew] [varchar](30) NULL,
[Date] [datetime] NULL
)
我该如何实现?
您基本上需要一个 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
除了@marc_s提到的触发选项,如果你想不仅仅考虑位置,还考虑所有列的变化审计,下面的选项提供你做审计,没有任何特定的编程需要。您可以看看它是否适合您的需求。
你可以想到SQL Server Temporal Tables。 Read on SQL Server Temporal Tables on MSDN。它们提供透明的方式来审核行更改。
您还可以使用更改数据捕获选项来跟踪列的历史更改。 Change Data Capture on MSDN
我有一个 table 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
)
每当 Position
(以及 Old Position
、New Position
和 Timestamp
) 在 Employee
table.
CREATE TABLE [dbo].[Employee_Audit]
(
[EmployeeCode] [int] NOT NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Email] [varchar](50) NULL,
[PositionOld] [varchar](30) NULL,
[PositionNew] [varchar](30) NULL,
[Date] [datetime] NULL
)
我该如何实现?
您基本上需要一个 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
除了@marc_s提到的触发选项,如果你想不仅仅考虑位置,还考虑所有列的变化审计,下面的选项提供你做审计,没有任何特定的编程需要。您可以看看它是否适合您的需求。
你可以想到SQL Server Temporal Tables。 Read on SQL Server Temporal Tables on MSDN。它们提供透明的方式来审核行更改。
您还可以使用更改数据捕获选项来跟踪列的历史更改。 Change Data Capture on MSDN