Best Practices

Triggers are really just stored procedures in disguise. They have a few additional capabilities and nuances, but generally speaking, you take the same approach to writing a trigger as you would to build a stored procedure. A few additional thoughts:

  • Make sure your triggers allow for the possibility that more than one row could be altered at once. Triggers that work fine with single-row operations often break when multirow operations come their way. Not allowing for multirow updates is the single most common error that trigger neophytes make.

  • Begin each trigger by checking @@ROWCOUNT to see whether any rows have changed. If none have, exit immediately because there's nothing for the trigger to do.

  • Use the UPDATE() and COLUMNS_UPDATED() ...

Get Guru's Guide to SQL Server™ Stored Procedures, XML, and HTML, The now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.