Gotcha alert re Need help tuning an on update trigger to honor a where clause.
SQL Server 2008. Main table has, say, 12345 rows. My intent is, on update I want to copy only the records being updated to a history table when an update is done. On updating with a where clause, I am finding that the trigger is transfering the entire table instead of just the records affected as limited by the where clause.
The History table in Production does not have the same data structure as Development, so I copied/pasted the Prod structure from Select. Not a SQL Server guru, I did not notice that I had missed from insert
from my Dev trigger and left the actual table name from the Select in the trigger on Prod:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE trigger [dbo].[myTable_LogUpdate]
ON [dbo].[myTable]
FOR UPDATE
AS
INSERT INTO myTable_Hist ([ID], [FLD_1], ..., [FLD_N], [HIST_DT])
SELECT
[ID], [FLD_1], ..., [FLD_N], GETDATE() AS HIST_DT
FROM
[dbo].[myTable] -- <<< this should be FROM inserted
GO
EXEC sp_settriggerorder @triggername=N'[dbo].[myTable_LogUpdate]', @order=N'Last', @stmttype=N'UPDATE'
GO
When I run an update with a where clause to update, say, 5 records:
USE [myDb]
update myTable
set FLD_7 = 2
where FLD_1 = 10 and FLD_2 = 20
In messages I get 2 responses:
(12345 rows affected)
(5 rows affected)
and running a count(*) before and after of the history table shows that all 12345 rows have been inserted into the myTable_LogUpdate
table (which is now gargantuan and desperately in need of clean-up).
Update: I had to delete the original Prod trigger because the drive had run out of disk space. The trigger code in my original post was from Dev so it was showing the correct code instead of the actual troubled trigger code I had been running on Prod. There was no way for any SO guru to answer the problem I had because the OP was not the bug.
I have updated the OP to reflect what the problem code was, with a notation where the correction needed to be. I have recreated the history table, fixed the trigger to be from inserted
and it works properly now.
Thank you to Sean, whose comments led me to this revelation.