Why use triggers in Microsoft SQL Server?

What are triggers:

Triggers are a special type of stored procedure which are executed automatically based on the occurrence of a database event. These events can be categorized as

  1. Data Manipulation Language (DML) and
  2. Data Definition Language (DDL) events.
The benefits derived from triggers is based in their events driven nature. Once created, the trigger automatically fires without user intervention based on an event in the database.

A) Using DML Triggers:

DML triggers are invoked when any DML commands like INSERT, DELETE, and UPDATE happen on the data of a table and or view.

Points to remember:

  1. DML triggers are powerful objects for maintaining database integrity and consistency.
  2. DML triggers evaluate data before it has been committed to the database.
  3. During this evaluation following actions are performed.
    • Compare before and after versions of data
    • Roll back invalid modification
    • Read from other tables ,those in other database
    • Modify other tables, including those in other database.
    • Execute local and remote stored procedures.
     
  4. We cannot use following commands in DML trigger
    • ALTER DATABASE
    • CREATE DATABASE
    • DISK DATABASE
    • LOAD DATABASE
    • RESTORE DATABASE
     
  5. Using the sys.triggers catalog view is a good way to list all the triggers in a database. To use it, we simply open a new query editor window in SSMS and select all the rows from the view as shown below;
    select * from sys.triggers
So let us create DML trigger.

You can create and manage triggers in SQL Server Management Studio or directly via Transact-SQL (T-SQL) statements.

1) Using AFTER triggers:

  • An AFTER trigger is the original mechanism that SQL Server created to provide an automated response to data modifications
  • AFTER triggers fire after the data modification statement completes but before the statement's work is committed to the databases.
  • The trigger has the capability to roll back its actions as well as the actions of the modification statement that invoked it.

Comments

Popular posts from this blog

Validate Mobile Number with 10 Digits in ASP.Net