Fairly new to SQL here… I am trying to get an ‘after update’ trigger in SQL Server to update a column (rig_ident
) whenever another column (rig_id
) is updated. rig_ident
is found by searching the rig_log
table.
With the below code it works, but I’m worried it may be running through every row in the table and checking accordingly, which would be a waste of processing and time! Can anyone provide suggestions on how to do this properly?
ALTER TRIGGER engineer_log_onUpdate_trig ON engineer_log AFTER UPDATE AS BEGIN SET NOCOUNT ON; IF (UPDATE(rig_id)) BEGIN DECLARE @rigNum AS int DECLARE @rigId AS int SELECT @rigNum = i.rig_id FROM inserted i --get the updated rig id value --get the required rig ident value from rig_log table... SELECT @rigId = ident FROM rig_log WHERE rig_id = @rigNum --try to update the rig_ident column of the row the user is updating... UPDATE engineer_log SET rig_ident = @rigId WHERE rig_id = @rigNum END END
Advertisement
Answer
Your trigger is broken (as the comment suggests) because you are assuming that only one row is being updated/inserted. But SQL Server triggers work on sets of rows, not on individual rows.
I think you can replace the logic with:
UPDATE el SET rig_ident = rl.ident FROM engineer_log el JOIN rig_log rl ON rl.rig_id = el.rig_id JOIN inserted i ON i.rig_id = rl.rig_id WHERE rig_id = @rigNum;