2013-07-16 162 views
0

我有一個觸發器應該在更新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 
+0

也許發佈您的解決方案......作爲*附加編輯*到您的原始文章.......所以其他人可以看到你最終做了什麼。保持您的原始文本「完整」,以便清楚地看到原始問題。 – granadaCoder

回答

1

你基本上有一個 「交叉聯接」 與此查詢

inserted I, deleted D 

3×3

注意,如果我運行此查詢...

Use Northwind 
GO 

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

我得到「x squared」作爲返回的行數,其中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平方行」......

+0

交叉連接是問題所在。 – user2425056