A trigger is a spacial type of stored procedure which is created on a particular table and it gets executed in response to certain events (insert, update, delete) on that table. It is a database object which is bound to a table. You can not invoke it explicitly. SQL Server engine executes it implicitly when an event occurs on that table.
In SQL server there are two types of triggers.
1. After Trigger (For Trigger)
2. Instead of Trigger
After Trigger
After trigger is also called as For trigger. It gets fired after an insert or delete or update on a table.
Example: After a new employee record is inserted in employee table you want to insert a record in your Audit table saying "A new employee with name XYZ is added at 8 Aug 2017 5:17 PM".
Before demonstrating this, let me explain about Magic tables.
Magic tables in SQL Server:
-Magic tables are temporary tables created by SQL server internally every time when a DML action is performed on a table with trigger . There are two magic tables
1. Inserted
2. Deleted
- These tables get created with same structure as like base table. It is not possible to see these table directly. These can only be accessed through triggers.
-When a new record inserted in base table, SQL server inserts a replica of the record in 'Inserted 'table.
-When a record deleted from base table, SQL server inserts a replica of the deleted record in 'deleted' table.
Now to see how to use Triggers let's first create a table 'Employee' and insert some records into it
Before demonstrating this, let me explain about Magic tables.
Magic tables in SQL Server:
-Magic tables are temporary tables created by SQL server internally every time when a DML action is performed on a table with trigger . There are two magic tables
1. Inserted
2. Deleted
- These tables get created with same structure as like base table. It is not possible to see these table directly. These can only be accessed through triggers.
-When a new record inserted in base table, SQL server inserts a replica of the record in 'Inserted 'table.
-When a record deleted from base table, SQL server inserts a replica of the deleted record in 'deleted' table.
Now to see how to use Triggers let's first create a table 'Employee' and insert some records into it
The Employee table now looks like this
Next, create an Audit table say 'Employee_Audit'
Now create an After trigger on Employee table to insert a record into Employee_Audit table automatically after insertion of a new record into 'Employee' table
Instead of Trigger
Instead of trigger is executed automatically in place of an insert or delete or update on a table.
Example: When any one tries to delete an employee's record from employee table you want to show an error message "You are not permitted to perform this action"; instead of the actual delete action.
Comments
Post a Comment