I have a table MyTable with a trigger defined like this:
ALTER TRIGGER [MyTableInsertDeleteUpdate] ON [dbo].[MyTable] AFTER INSERT,DELETE,UPDATE AS DECLARE @id int; BEGIN SELECT @id = ins.id FROM inserted ins; IF (@id IS NOT NULL) BEGIN -- insert a new record to audit table PRINT 'inserted/updated id: ' + CAST(@id AS VARCHAR); END END
I realize that if more than one rows are updated like this,
UPDATE MyTable SET name = 'test rows' WHERE id in (1, 2, 3);
the tigger is called only once and only the firstone in [inserted] is updated. Actually, [inserted] may have more than one rows (3 in this case if id 1, 2,3 exist). In order words, the trigger is not fired on each row. Is that right?
I am using Microsoft SQL Server 2005.
Yeah the trigger is fired once per statement (not once per row) that makes the changes you are subscripting to. It will even fire if no rows where affected.
http://msdn.microsoft.com/en-us/library/ms189799(SQL.90).aspx