Triggers in SQL are essentially automated actions that the database can take in response to certain events. They are special types of stored procedures and are executed automatically when specific events, like INSERT, UPDATE, or DELETE, occur in the database.
Here's why triggers are useful:
In this scenario, we want to maintain an audit trail for changes to an "Employees" table. When there's an update to the "Salary" column, the change gets logged into a "SalaryAudit" table.
CREATE TRIGGER tr_AfterUpdateSalary
ON Employees
AFTER UPDATE
AS
BEGIN
IF UPDATE(Salary)
BEGIN
INSERT INTO SalaryAudit (EmployeeID, OldSalary, NewSalary, AuditDate)
SELECT d.EmployeeID, d.Salary, i.Salary, GETDATE()
FROM inserted i
JOIN deleted d ON i.EmployeeID = d.EmployeeID;
END
END;
Assume you want to ensure that no records are accidentally deleted from the "Products" table. A trigger can be used to prevent such actions.
CREATE TRIGGER tr_PreventDeleteProducts
ON Products
INSTEAD OF DELETE
AS
BEGIN
PRINT 'Deletion not allowed on Products table!';
ROLLBACK TRANSACTION;
END;
For a "Comments" table, every time a comment is updated, you might want to automatically update a "LastModified" timestamp column.
CREATE TRIGGER tr_UpdateCommentTimestamp
ON Comments
AFTER UPDATE
AS
BEGIN
UPDATE Comments
SET LastModified = GETDATE()
WHERE CommentID IN (SELECT CommentID FROM inserted);
END;
Triggers offer an automated and robust way to enforce rules, react to data changes, and maintain data integrity within SQL databases. By understanding and utilizing triggers effectively, developers can create more reliable and self-sustaining database applications.