Sql update trigger only when column is modified
To trigger an update only when a certain column changes, craft a conditional trigger that checks for before and after values of that column. Here's how you cook it hot in SQL:
Tip: Substitute your_table
, column_name
, and id
with your own table, column, and id field. The trigger swings into action only if column_name
becomes the eye of change.
Taking charge of column change
When you action an update to your table, SQL Server gets moving with the Inserted
and Deleted
temporary tables. They're the fellows holding the new and old values of the column. We can play these two off against each other to see if column_name
took a wardrobe change.
Updating modification deets
When column_name
is spotted with a change, we mark the Modified
, ModifiedUser
, and ModifiedHost
fields about when this change happened, who did it, and from which host. They report for duty through GETDATE()
, SUSER_NAME()
, and HOST_NAME()
functions.
Performance tweak with SET NOCOUNT ON
By sticking SET NOCOUNT ON
atop your trigger, you forestall the dispatch of row count messages. This saves your computer breath and shaves off network traffic.
How to make sense of the trigger
Let's decipher this with a real-world table inventory
having a column QtyToRepair
that you wish to monitor for updates:
Points to ponder:
- The trigger is tailored to respond when
QtyToRepair
is updated. IF UPDATE(QtyToRepair)
be the gatekeeper, letting only those updates through whereQtyToRepair
is part of the bargain.- The dance between the
Inserted
andDeleted
tables filters out updates whereQtyToRepair
is just messing with you and hasn't essentially changed.
All you need to know about trigger best practices
Push for speedy performance
When sketching your trigger, always consider its performance impact. A lagging trigger can bog down your database operations. So, wear down its logic to the bare minimum for ultimate speed.
Buff up error management
Arm your triggers with error handling to tackle inconsistencies or hurdles during execution. This can be a life-saver, keeping your database from collapsing into an inconsistent state if the chips fall wrong.
Sync with the business logic
Ensure your trigger is singing the same song as your business requirements. Put down its purpose eloquently and double-check that it doesn't enforce contradicting rules against your application's tune.
Prioritize alternative solutions
If triggers seem to be falling short, take a detour. Consider other options like stored procedures or managing column updates at the application level which can offer more command and flexibility.
Was this article helpful?