~ 7 min read

SQL Server Triggers

By: Adam Richardson
Share:

What are SQL Server Triggers?

SQL Server Triggers are special types of stored procedures that are automatically executed in response to certain events or changes occurring in a SQL Server database. When the specified event occurs, the trigger executes its associated Transact-SQL code, allowing developers to automate certain processes, enforce data integrity, and enhance performance.

Triggers can be defined to execute either before or after the event that triggers them. Before triggers run before the operation occurs, and after triggers run after the operation occurs. The most commonly used events that can trigger a trigger are INSERT, DELETE, and UPDATE operations on a table.

For example, let’s say that you have a table that contains information about orders in a retail system. You want to track which user updated an order, and when it was updated. You can create an update trigger that will update the ‘LastUpdatedBy’ and ‘LastUpdatedDate’ columns in the ‘Orders’ table whenever the ‘OrderStatus’ column is updated:

CREATE TRIGGER trg_Update_Order_Status
ON Orders
AFTER UPDATE
AS
BEGIN
    IF UPDATE(OrderStatus)
    BEGIN
        UPDATE Orders
        SET LastUpdatedBy = SYSTEM_USER,
            LastUpdatedDate = GETDATE()
        FROM inserted
        WHERE Orders.OrderID = inserted.OrderID
    END
END

In this example, the trigger is defined to execute AFTER UPDATE of the Orders table. The trigger’s T-SQL code updates the LastUpdatedBy and LastUpdatedDate columns in the Orders table base on the OrderStatus column update. The inserted table is a special table that is created by SQL Server and contains the new values that have been inserted, updated or deleted in the Order table.

The use of triggers in SQL Server can greatly improve database performance and ensure data integrity. When used correctly, triggers can also help automate certain processes and reduce the amount of manual intervention required. It’s important, however, to use triggers sparingly and to ensure that they do not negatively impact database performance.

Types of Triggers in SQL Server

In SQL Server, there are two types of triggers that can be defined: DML (Data Manipulation Language) triggers and DDL (Data Definition Language) triggers.

DML triggers are used to enforce business rules and other types of constraints on the data stored in tables. They are fired in response to INSERT, UPDATE, or DELETE events on tables. These types of triggers are commonly used to ensure data integrity, to enforce rules that cannot be defined using constraints or other mechanisms, and to audit data modifications.

DDL triggers, on the other hand, are used to capture events that affect the database structure itself. They can be fired in response to events such as CREATE, ALTER, and DROP statements that create, modify, or delete database objects such as tables, views, or stored procedures. DDL triggers can be used to prevent unauthorized changes to database objects, or to capture information about changes that are made.

Here’s an example of a DML trigger that prevents an UPDATE operation on an ‘Employees’ table under certain conditions:

CREATE TRIGGER trg_Employees_Update
ON Employees
INSTEAD OF UPDATE
AS
BEGIN
    IF EXISTS(SELECT * FROM inserted WHERE Salary > 10000)
        RAISERROR('Salary cannot be updated for this employee', 16, 1)
    ELSE
        UPDATE Employees
        SET Name = i.Name,
            Salary = i.Salary,
            HireDate = i.HireDate
        FROM Employees e
        INNER JOIN inserted i
        ON e.EmployeeID = i.EmployeeID
END

In this example, the trigger is defined to execute INSTEAD OF UPDATE of the Employees table. The trigger’s T-SQL code first checks if any updated rows in the inserted table have a Salary value greater than 10000. If this condition is met, it raises an error message that prevents the update from occurring. Otherwise, it proceeds with updating the Employees table with the new data from the inserted table.

In summary, DML triggers are used to ensure data integrity and to audit data modifications, while DDL triggers capture events that affect the database structure itself. Knowing the differences between these two types of triggers can help developers design better and more effective database solutions for their projects.

Creating and Editing Triggers in SQL Server

Creating and editing triggers in SQL Server is a straightforward process that can be performed using Transact-SQL (T-SQL) statements. To create a new trigger, you’ll need to use the CREATE TRIGGER statement, specifying the table and event that will trigger the trigger, as well as the T-SQL code that will be executed when the trigger fires.

Here’s an example of how to create a trigger that logs changes made to an Orders table:

CREATE TRIGGER trg_Orders_LogChanges
ON Orders
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    IF @@ROWCOUNT = 0
        RETURN

    DECLARE @Event VARCHAR(10)

    IF EXISTS(SELECT * FROM inserted)
    BEGIN
        IF EXISTS(SELECT * FROM deleted)
            SET @Event = 'UPDATE'
        ELSE
            SET @Event = 'INSERT'
    END
    ELSE
        SET @Event = 'DELETE'

    INSERT INTO OrdersChanges (OrderID, ChangeDate, ChangeType)
    SELECT OrderID, GETDATE(), @Event
    FROM inserted
END

In this example, the trigger is defined to execute AFTER INSERT, UPDATE, DELETE on the Orders table. The @@ROWCOUNT = 0 condition checks if any rows were affected by the trigger event. The trigger’s T-SQL code then determines the type of event that occurred (INSERT, UPDATE, or DELETE) and inserts a row into a OrdersChanges log table with the affected OrderID, the current date/time, and the type of change that occurred.

To edit an existing trigger, you can use the ALTER TRIGGER statement to modify the trigger’s T-SQL code, or to change the table or event that triggers the trigger.

ALTER TRIGGER trg_Employees_Update
ON Employees
FOR UPDATE
AS
BEGIN
    -- New T-SQL code for the trigger
END

In this example, the ALTER TRIGGER statement is used to modify the trg_Employees_Update trigger on the Employees table by changing the triggering event to FOR UPDATE instead of INSTEAD OF UPDATE.

Examples of Trigger Implementation in SQL Server

SQL Server Triggers can be used in a variety of ways to automate processes, enforce constraints, and audit data modifications. Here are a few examples of how triggers can be implemented in SQL Server:

  1. Audit Data Modifications: You can use triggers to record changes made to a table in an audit log. This can be useful for tracking who made changes, when they were made, and what was changed. For example, you can create a trigger on an Orders table that logs changes to a OrdersChanges table:
CREATE TRIGGER trg_Orders_LogChanges
ON Orders
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    IF @@ROWCOUNT = 0
        RETURN

    DECLARE @Event VARCHAR(10)

    IF EXISTS(SELECT * FROM inserted)
    BEGIN
        IF EXISTS(SELECT * FROM deleted)
            SET @Event = 'UPDATE'
        ELSE
            SET @Event = 'INSERT'
    END
    ELSE
        SET @Event = 'DELETE'

    INSERT INTO OrdersChanges (OrderID, ChangeDate, ChangeType)
    SELECT OrderID, GETDATE(), @Event
    FROM inserted
END
  1. Prevent Data Modifications: You can use triggers to prevent certain modifications to a table, based on business rules or other criteria. For example, you can create a trigger on an Employees table that prevents salary updates for employees with a salary greater than 10000:
CREATE TRIGGER trg_Employees_PreventSalaryUpdates
ON Employees
INSTEAD OF UPDATE
AS
BEGIN
    IF EXISTS(SELECT * FROM inserted WHERE Salary > 10000)
        RAISERROR('Salary cannot be updated for this employee', 16, 1)
    ELSE
        UPDATE Employees
        SET Name = i.Name,
            Salary = i.Salary,
            HireDate = i.HireDate
        FROM Employees e
        INNER JOIN inserted i
        ON e.EmployeeID = i.EmployeeID
END
  1. Enforce Data Integrity: You can use triggers to enforce referential integrity or other constraints on a table. For example, you can create a trigger on an OrderDetails table that prevents updates to the ProductID column if the corresponding Product row is deleted:
CREATE TRIGGER trg_OrderDetails_PreventProductIDUpdates
ON OrderDetails
INSTEAD OF UPDATE
AS
BEGIN
    UPDATE OrderDetails
    SET ProductID = i.ProductID,
        Quantity = i.Quantity,
        Price = i.Price
    FROM OrderDetails od
    INNER JOIN inserted i
    ON od.OrderDetailID = i.OrderDetailID
    INNER JOIN Products p
    ON i.ProductID = p.ProductID

    IF @@ROWCOUNT > 0
        RAISERROR('Cannot update ProductID. Product is deleted', 16, 1)
END

In summary, SQL Server triggers can be used to automate processes, enforce constraints, and audit data modifications. By using triggers effectively, developers can improve database performance and ensure data integrity in their applications.

Summary

SQL Server Triggers are a powerful mechanism that can be used to automate processes, enforce data integrity, and audit data modifications in SQL Server databases. By using triggers effectively, developers can save time and reduce the risk of data errors or inconsistencies. In this article, we have covered the basics of triggers in SQL Server, including their types and how to create and edit them. We have also given some examples of how triggers can be implemented in different scenarios. If you are a SQL Server developer or administrator, it is important to have a good understanding of triggers and how they can be used to improve database performance and ensure data integrity.

Share:
Subscribe to our newsletter

Stay up to date with our latest content - No spam!

Related Posts