表更新的触发器触发的次数超过了更新的行数

时间:2013-07-16 19:03:22

标签: sql-server triggers sql-server-2012-express

我有一个触发器,应该在更新触发器设置为ON的EmployeeSalaryHistory表时将新记录插入审计历史记录表(Employees)。

如果我在UPDATEEmployees执行表中所有行的更新,则会调用触发器的次数超过正在更新的行数。

e.g。如果Employees表中有三行,则INSERT会发生9次。

/*This UPDATE will cause the trigger to fire more than the number of rows in the Employees table.*/
UPDATE Employees SET Salary = Salary * 2 

/* supposed to be fired whenever the salary of an employee is updated */
CREATE TRIGGER [dbo].[EmployeesUpdateSalary] ON [dbo].[Employees]
AFTER UPDATE
NOT FOR REPLICATION
AS
BEGIN

INSERT INTO EmployeeSalaryHistory(EmployeeID, NewSalary, OldSalary)
SELECT I.EmployeeID, I.Salary, D.Salary
From inserted I, deleted D
WHERE I.Salary <> D.Salary

END

1 个答案:

答案 0 :(得分:1)

您基本上与此查询“交叉连接”

inserted I, deleted D

3 x 3

注意,如果我运行此查询......

Use Northwind
GO

Select * from
[dbo].[Categories] c1 , [dbo].[Categories] c2

我得到了“x平方”作为返回的行数,其中x是[dbo]。[Categories]表中的行数。

修改

试试这个

INSERT INTO EmployeeSalaryHistory(EmployeeID, NewSalary, OldSalary)
SELECT I.EmployeeID, I.Salary, D.Salary
From inserted I, deleted D
where I.EmployeeID = D.EmployeeID /* relationship */
and
I.Salary <> D.Salary /* filter */

或者

INSERT INTO EmployeeSalaryHistory(EmployeeID, NewSalary, OldSalary)
SELECT I.EmployeeID, I.Salary, D.Salary
From inserted I join deleted D on I.EmployeeID = D.EmployeeID /* relationship */
Where
I.Salary <> D.Salary /* filter */

将其带回通用示例:

    Use Northwind
    GO
Select * from
[dbo].[Categories] c1 , [dbo].[Categories] c2
Where c1.CategoryID = c2.CategoryID

将有“x行”,而不是“x平方行”......