Search⌘ K

Triggers

Explore how to implement triggers in T-SQL to automatically perform actions on data changes. Understand the differences between AFTER and INSTEAD OF triggers, and learn to use deleted and inserted tables within triggers for effective database logging and management.

Triggers are a special type of stored procedure that is automatically called when a certain action is performed on a table. For example, we can use triggers to perform an action when a row is inserted into a table, deleted from it, or data is modified.

Triggers are similar to functions and stored procedures in the sense that they have a body that is executed when the trigger is called.

The AFTER triggers

Triggers are called when there is a change in a table’s state. For example, a trigger may be executed after a row is deleted from a table.

Syntax

There are three types of AFTER triggers:

  • AFTER DELETE means that this trigger is executed when a row is deleted from the TableName table:

    CREATE TRIGGER TriggerName
    ON TableName
    AFTER DELETE
    AS
        [Trigger body]
    
  • AFTER INSERT means that the trigger is called after a new row is inserted into a table:

    CREATE TRIGGER TriggerName
    ON
...