In this article, I am going to explain you AFTER Delete Trigger in SQL-Server with example. In the previous tutorial, I have explained introduction to triggers in SQL-Server. Please go through the links provided below.
Related Links
Introduction to triggers in SQL-Server.After INSERT Trigger in SQL Server with example.
AFTER Delete Trigger (for delete) with Example
When we try to delete records from a Table then delete trigger is fired if trigger is associated with that table. After Delete trigger is also called as For Delete trigger. Now, let's implement after delete trigger.
Create a table Employee with four columns EmployeeId, Name, Age and gender. EmployeeId will be auto generated. Below is the code to create Employee table and insert some dummy records.
Now, execute the select query to check inserted records.
OUTPUT:
Now, we will create a Audit Table for Employee table. When somebody delet record of Employee table, then we will insert same record in audit table by using after delete trigger. Below is the script to create Employee_Audit table.
Creating AFTER Delete Trigger
Now, we will create after delete trigger. Below is the script to create after update trigger.
When you delete a record of Employee table then SQL-Server creates a magic table named as 'deleted' and same copy of record will we inserted into this magic table. Deleted table is accessible inside the context of trigger. You can not access deleted table outside of triggers.
Executing After Delete Trigger
As we can not execute triggers explicitly, to execute trigger, we need to delete an record from the table. Execute below query to delete record from Employee table whose EmployeeId is 1.
As you can see below a record will be deleted for Employee table and a new will be inserted for Employee_Audit table.
Employee Table:
Now truncate both the tables and again insert same record (5 records) into Employee table. Now try to delete multiple records at single time. Execute below query to delete multiple records and select from both the tables.
As you can see from above output, two records are deleted from Employee table and only one record is inserted into Employee_Audit table because delete trigger fires only once per action.
Now to prevent from this, we will alter the procedure as shown below. We will directly use deleted table to insert into audit table.
Now truncate both the tables and again insert same record (5 records) into Employee table. Now try to delete multiple records at single time. Execute below query to delete multiple records and select from both the tables.