Theme-Logo
  •   .Net
    •   C Sharp(C#)
    •   Web API
    •   Micro Services
    •   ASP.Net
    • ASP.Net MVC
    • .Net Core
  •   Database
    • SQL Server
    • Oracle
    • PostgreSQL
  •   jQuery
    • jQuery Tutorials
    • jQuery Plugins
    • jQuery UI
    • More on jquery
  •   Tutorials
    • Microservices Tutorials
    • DotNet Core Tutorials
    • PostgreSql Tutorials

Trigger in SQL Server

A trigger is a stored procedure in database which automatically invokes whenever a special event in the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when certain table columns are being updated.

A trigger runs automatically when an event occurs. There are three different types of events on which a trigger can run/fired automatically:

  • DML Trigger Events
  • DDL Trigger Events
  • LOGON Trigger Event – Logon trigger is fired when a LOGON event occurs i.e. when a user session is being established
  • DML Triggers in SQL Server

    DML triggers in SQL Server are fired when a DML event occurs. i.e. when data is inserted/ updated/deleted in the table by a user.

    We can create a DML trigger for a specific event or multiple events. The triggers in SQL Server(DML) fire on events irrespective to the number of rows affected.

    These triggers are created at the table level. Upon successful creation of trigger, we can see the triggers by navigating to Triggers folder at table level.

                                CREATE TRIGGER TR_UPD_Locations ON Locations
                                FOR UPDATE 
                                NOT FOR REPLICATION 
                                AS
     
                                BEGIN
                                  INSERT INTO LocationHist
                                  SELECT LocationID
                                    ,getdate()
                                  FROM inserted
                                END
                            
    Instead of triggers in SQL Server

    These triggers are fired before the DML event and the actual data is not modified in the table. For example, if we specify an instead of trigger for delete on a table, when delete statement is issued against the table, the instead of trigger is fired and the T-SQL block inside the triggers in SQL Server is executed but the actual delete does not happen.

  • If there are multiple triggers along with instead of trigger on the table, the instead of trigger is fired first in the order
  • INSTEAD of triggers can be created on views
  • we can define only one instead of trigger per INSERT, UPDATE, or DELETE statement on a table or view
  • DDL Triggers in SQL Server

    DDL triggers in SQL Server are fired on DDL events. i.e. against create, alter and drop statements, etc. These triggers are created at the database level or server level based on the type of DDL event.

    These triggers are useful in the below cases.

  • Prevent changes to the database schema
  • Audit database schema changes
  • To respond to a change in the database schema
  • Below is the sample syntax for creating a DDL trigger for ALTER TABLE event on a database w hich records all the alter statements against the table. You can write your custom code to track or audit the schema changes using EVENTDATA().

                               CREATE TABLE TableSchemaChanges (ChangeEvent xml, DateModified datetime)
     
                                CREATE TRIGGER TR_ALTERTABLE ON DATABASE
                                FOR ALTER_TABLE
                                AS
                                BEGIN
     
                                    INSERT INTO TableSchemaChanges
                                    SELECT EVENTDATA(),GETDATE()
     
                                END
                            
    LOGON Triggers in SQL Server

    These triggers in SQL Server fire in response to a LOGON event. LOGON triggers fire after successful authentication and before establishing the user session.

    LOGON triggers are created at the server level and are useful below cases.

  • To audit login activity
  • To control the login activity
  • Direct recursion

    Direct recursion is a case where the SQL Server trigger on the table is fired and performs an action which again triggers the same trigger.

    Direct recursion can be controlled by a database setting RECURSIVE_TRIGGERS. If the setting is on, then the above trigger throws an error.

    To change RECURSIVE_TRIGGERS setting using SSMS, navigate to the database, right click on the database and select Properties. Click on Options and change the setting to the option you want.

    To set the RECURSIVE_TRIGGERS OFF using T-SQL, use below statement and replace the database name with your database name.

                                // FOR OFF
                                        ALTER DATABASE [AdventureWorks] SET RECURSIVE_TRIGGERS OFF WITH NO_WAIT
                                        GO
                                // FOR ON
                                       ALTER DATABASE [AdventureWorks] SET RECURSIVE_TRIGGERS ON WITH NO_WAIT
                                    GO
    

    SQL Server trigger order

    SQL Server allows multiple triggers on the table for the same event and there is no defined order of execution of these triggers. We can set the order of a trigger to either first or last using procedure sp_settriggerorder. There can be only one first or last trigger for each statement on a table.

    Not For Replication in SQL Server Trigger

    NOT FOR REPLICATION indicates that the trigger should not fire when the replication agent syncs the data changes to the subscriber. For example, if you are replicating both Locations and LocationHist. Now when you update a record on Location the trigger is fired, inserts record in the history table. When these changes sync to another end (subscribers) there is no need of trigger to be fired again. So, if we mark the trigger for “NOT FOR REPLICATION” the trigger does not fire when replication agent sync’s the changes and fires only for the data changes done by the user.

    Trending Post
    What is Anonymous methods in C#.
    Why Is It A Bad Idea To Throw Your Own Exceptions.
    How's The DLL Hell Problem Solved In .net?
    Interview Questions and Answers
    Describe the Async method of C#?
    Is it possible to serialise hashtables?
    Explain the differences between “out” and “ref” parameters in C#?
    How would you implement the Singleton design pattern in C#?
    What Are The Ways To Deploy An Assembly?
    What Are Advantages And Disadvantages Of Microsoft-provided Data Provider Classes In Ado.net?
    About us

    DotNet Palace is a community platform created and maintained by The articles are mainly focused on Microsoft stack technologies like C#, ASP.Net, MVC, .Net Core, SQL Server and Oracle, PostgreSQL, SQLite etc. To improve the site's content you can send your valuable suggestions at info.dotnetpalace@gmail.com

    Quick links
  • SOLID Principles
  • Questions
  • OOPS Principles
  • DotNet Palace Tutorials
  • Privacy Policy
  • Terms and Condition