Stored procedures are programmable blocks that are explicitly called and can accept parameters, execute complex business logic, work with transactions, and return data sets or output parameters.
Triggers are special objects that "automatically" fire on data modification events (INSERT, UPDATE, DELETE), ensuring transparent execution of specified logic during certain actions on a table.
When to use procedures
When to use triggers
Stored Procedure:
CREATE PROCEDURE UpdateProductPrice @ProductID int, @NewPrice money AS BEGIN UPDATE Products SET Price = @NewPrice WHERE ProductID = @ProductID; END
Trigger:
CREATE TRIGGER trg_ProductsPriceChange ON Products AFTER UPDATE AS BEGIN INSERT INTO PriceAuditLog(ProductID, OldPrice, NewPrice, ChangeDate) SELECT i.ProductID, d.Price, i.Price, GETDATE() FROM inserted i JOIN deleted d ON i.ProductID = d.ProductID WHERE i.Price <> d.Price END
Q: Can the order of execution of multiple AFTER triggers on the same table in SQL Server be determined by standard means?
A: No, the SQL standard does not guarantee the order of execution of AFTER triggers of the same type on the same table. If the order is important, they should be combined into one.
Story
In a CRM solution for supporting change history functionality, triggers were used. Due to the high load from mass updates, records in the log were entered with a delay and blocked "live" operations, causing temporary unavailability of the service.
Story
A developer created logic for data validation not in a procedure but in a trigger, expecting that users would see the changes instantly. Forgetting that the trigger is "transparent," they faced the situation where the business logic became non-obvious (like "magic") and was difficult to debug.
Story
Important: Often, a procedure is called within a trigger, or a trigger from a procedure, leading to recursion and exceeding the nesting limit—for example, automatic insertion leads to the trigger being fired again through the related procedure.