Triggers in SQL Server are unique stored procedures that are designed to execute automatically when certain events take place within the database. These events may involve data manipulation actions such as INSERT, UPDATE, or DELETE, as well as data definition actions including CREATE, ALTER, or DROP. Triggers can be categorized into two primary types.
- DML Triggers (Data Manipulation Language Triggers): These triggers activate in response to DML events, which encompass operations like INSERT, UPDATE, or DELETE.
- DDL Triggers (Data Definition Language Triggers): These triggers activate in response to DDL events, which include operations such as CREATE, ALTER, or DROP.
When to Use Triggers?
Triggers are used in various scenarios to ensure the automatic execution of specific actions in response to certain database events. Here are some common situations where triggers are beneficial.
- Audit Trails
- When: You need to track changes to important data for compliance, security, or historical analysis.
- Why: Triggers can automatically log changes to an audit table without requiring additional application code, ensuring consistent and reliable tracking.
- Enforcing Business Rules
- When: Business rules must be enforced directly at the database level to ensure data integrity and consistency.
- Why: Triggers ensure that business rules are applied uniformly, even if data is modified directly through SQL queries rather than through an application.
- Maintaining Referential Integrity
- When: You need to ensure that relationships between tables remain consistent, such as cascading updates or deletes.
- Why: Triggers can automatically handle referential integrity tasks, reducing the risk of orphaned records or inconsistent data.
- Synchronizing Tables
- When: You need to keep multiple tables synchronized, such as maintaining a denormalized table or a summary table.
- Why: Triggers can automatically propagate changes from one table to another, ensuring data consistency without manual intervention.
- Complex Validations
- When: Data validation rules are too complex to be implemented using standard constraints.
- Why: Triggers can perform intricate checks and validations on data before it is committed to the database.
- Preventing Invalid Transactions
- When: Certain operations should be blocked if they don't meet specific criteria.
- Why: Triggers can roll back transactions that violate predefined conditions, ensuring that only valid data modifications are allowed.
Why Use Triggers?
The main advantages of using triggers include.
- Automatic Execution: Triggers execute automatically in response to specified events, reducing the need for manual intervention and ensuring that critical actions are always performed.
- Centralized Logic: Business rules, validations, and data integrity checks can be centralized within triggers, making the system more maintainable and reducing code duplication across different parts of the application.
- Real-time Auditing: Triggers can create real-time audit logs, providing an accurate and up-to-date record of data changes without relying on external processes or applications.
- Complex Integrity Constraints: Triggers can enforce complex data integrity rules that are beyond the capabilities of standard SQL constraints, ensuring higher data quality and consistency.
- Data Consistency: Triggers help maintain data consistency by ensuring that related changes are applied across the database, preventing issues such as orphaned records or inconsistent states.
Benefits of Triggers
- Automated Execution: Triggers execute automatically in response to particular events, reducing the necessity for manual interference.
- Centralized Logic: Business regulations and data integrity checks can be centralized within triggers, enhancing system maintainability and reducing code repetition.
- Real-time Auditing: Triggers can be utilized to generate real-time audit logs of data alterations.
- Complex Integrity Checks: Triggers can enforce complex integrity checks that surpass the capabilities of standard SQL constraints.
- Data Uniformity: Triggers aid in upholding data uniformity by ensuring that associated modifications are implemented throughout the database.
SQL Server Triggers and their Special tables
Within SQL Server, there are special internal tables known as "magic tables" - INSERTED and DELETED. These tables are utilized within DML triggers to store the data that is being modified by the triggering action.
Understanding INSERTED and DELETED Tables
- The INSERTED table stores the affected rows during INSERT and UPDATE operations. During an INSERT operation, it holds the new rows being added to the table. In an UPDATE operation, it contains the new values post-update.
- The DELETED table, on the other hand, stores the affected rows during DELETE and UPDATE operations. In a DELETE operation, it contains the rows being removed from the table. For an UPDATE operation, it holds the old values before the update.
Example Logging Changes
Suppose we have an EmployeesDetails table and we want to create a trigger that logs all changes (inserts, updates, and deletes) to an EmployeesDetails _Log table.
SQL Script
CREATE TABLE EmployeesDetails (
EmployeeID INT PRIMARY KEY,
Name NVARCHAR(100),
Position NVARCHAR(100),
Salary DECIMAL(10, 2)
);
CREATE TABLE EmployeesDetails_Audit (
AuditID INT IDENTITY(1,1) PRIMARY KEY,
EmployeeID INT,
Name NVARCHAR(100),
Position NVARCHAR(100),
Salary DECIMAL(10, 2),
ChangeDate DATETIME DEFAULT GETDATE(),
ChangeType NVARCHAR(10)
);
CREATE TRIGGER trgEmployeesDetailsAudit
ON EmployeesDetails
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
IF EXISTS (SELECT * FROM inserted)
BEGIN
INSERT INTO EmployeesDetails_Audit (EmployeeID, Name, Position, Salary, ChangeType)
SELECT EmployeeID, Name, Position, Salary, 'INSERT'
FROM inserted;
END
IF EXISTS (SELECT * FROM deleted)
BEGIN
INSERT INTO EmployeesDetails_Audit (EmployeeID, Name, Position, Salary, ChangeType)
SELECT EmployeeID, Name, Position, Salary, 'DELETE'
FROM deleted;
END
END;
-- Insert sample items into the EmployeesDetails table
INSERT INTO EmployeesDetails (EmployeeID, Name, Position, Salary)
VALUES
(1, 'Alice Johnson', 'Software Engineer', 80000.00),
(2, 'Bob Smith', 'Project Manager', 95000.00),
(3, 'Charlie Davis', 'Analyst', 60000.00),
(4, 'Diana Wilson', 'UX Designer', 72000.00),
(5, 'Edward Brown', 'Database Administrator', 85000.00);
SELECT * FROM EmployeesDetails;
SELECT * FROM EmployeesDetails_Audit;
Query Window
Execution of trigger