我需要编写一个AFTER UPDATE触发器。当员工表的工资率被修改时。它需要获取该信息并在ChangeLog表中创建一行。我的表格如下:
员工:
EmployeeID INT (PK),
PayPerHour MONEY
更新日志:
ChangeID INT (PK),
EmpID (FK to EmployeeID),
ChangedBy NVARCHAR(30),
DateChanged SMALLDATETIME,
OldRate MONEY,
NewRate MONEY
这是我放在一起的东西。没有错误,但它没有在ChangeLog中创建行。 (我的印象是插入=新数据,删除=旧数据)。理想情况下,EmpID将匹配,ChangedBy将是系统用户,DateChanged将是时间戳,OldRate将是预先更新的速率,NewRate将是更新后的速率。
CREATE TRIGGER PayRate_UPDATE
ON Employees
AFTER UPDATE
AS
BEGIN
DECLARE @EmpID INT
SELECT @EmpID = EmployeeID
FROM inserted
DECLARE @OldRate MONEY
SELECT @OldRate = PayPerHour
FROM deleted
DECLARE @DateChanged SMALLDATETIME
SELECT @DateChanged = GETDATE()
DECLARE @ChangedBy NVARCHAR(128)
SELECT @ChangedBy = suser_sname()
DECLARE @NewRate MONEY
SELECT @NewRate = PayPerHour
FROM inserted
IF UPDATE(PayPerHour)
UPDATE ChangeLog
SET EmpID = @EmpID,
ChangedBy = @ChangedBy,
DateChanged = @DateChanged,
OldRate = @OldRate,
NewRate = @NewRate
END;
答案 0 :(得分:4)
您的代码中存在一些问题:
您的代码应该更像:
my $a = $1 if $s =~ s/^$m *: (.*?)$/$1/rsm;
my $b = $1 if $s =~ s/^$m *: (.*)$/$1/rm;
因此,修订后的触发器现在可以处理每个人都有加薪的情况,例如
CREATE TRIGGER PayRate_UPDATE ON Employees
AFTER UPDATE
AS
BEGIN
DECLARE @DateChanged SMALLDATETIME
SELECT @DateChanged = GETDATE()
DECLARE @ChangedBy NVARCHAR(128)
SELECT @ChangedBy = SUSER_SNAME()
IF UPDATE(PayPerHour)
INSERT [ChangeLog]
(
EmpID,
ChangedBy,
DateChanged,
OldRate,
NewRate
)
SELECT
i.EmployeeID,
@ChangedBy,
@DateChanged,
d.PayPerHour,
i.PayPerHour
FROM
INSERTED i
LEFT JOIN DELETED d
ON i.EmployeeID = d.EmployeeID
END;
并且您的更改日志会保留每个员工支付率的每次更新历史记录。