想要记录该字段的原值和现有值,触发器写法:
CREATE TRIGGER tr_UpdateEmployeeDepartment
ON Employees
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON; -- 避免多余的计数消息
IF UPDATE(Department) -- 检查是否更新了 Department 字段
BEGIN
INSERT INTO UpdateLog (EmployeeID, FieldName, OldValue, NewValue)
SELECT
inserted.EmployeeID,
'Department',
deleted.Department,
inserted.Department
FROM
inserted
INNER JOIN
deleted ON inserted.EmployeeID = deleted.EmployeeID;
END
END;