【问题标题】:Trigger on table update is firing for more than the number of rows updated表更新触发器触发的行数超过更新的行数
【发布时间】:2013-07-16 19:03:22
【问题描述】:

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

如果我在Employees 上执行UPDATE,其中表中的所有行都已更新,则调用触发器的次数多于正在更新的行数。

例如如果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

【问题讨论】:

  • 也许可以发布您的解决方案......作为附加编辑到您的原始帖子.......这样其他人就可以看到您最终做了什么结束。保持原始文本“完整”,以便清楚地看到原始问题。

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


【解决方案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 平方行”......

【讨论】:

  • 交叉连接是问题所在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
  • 2013-01-02
相关资源
最近更新 更多