Tuesday, October 16, 2007

Triggers that cater for multiple record updates / deletes.

I recently experienced a probelm with SQL Server triggers not enumerating through multiple records, in a batch delete. I was uing using variables in the T-SQL statements as follows;

Select @masterID = master_id, @value = the_value from

update table_name set field_name = field_name - @value
where id = @masterId

I was assuming the trigger would fire for each record deleted. Not so.

If “deleted” contains more than one record, this update statement will only be executed for one of them, and it’s difficult to predict which one.


You need to combine the update and select statement to achieve the same thing, in one T-SQL statement.

update table_name
set field_name = field_name – the_value
table_name tn
left join deleted d on tn.id = d.master_id
tn.id = d.master_id