我有一张桌子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
(以及Position
,Old Position
和New Position
)中有变化时,我都想在Timestamp
表中记录更改{1}}表。
Employee
我该如何实现?
答案 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之外,如果您不只是考虑位置,并考虑所有列更改审核,下面的选项可让您进行审核,而无需任何特定的编程需求。您可以查看它是否适合您的需求。
您可以想到SQL Server临时表。 Read on SQL Server Temporal Tables on MSDN。它们提供了透明的方式来审计行更改。
您还具有“更改数据捕获”选项,以跟踪列的历史更改。 Change Data Capture on MSDN