What is a trigger in the SQL server?
How To Create SQL Server Trigger For Update Event?
Let’s create a SQL server trigger for an update event that will get executed once a row is updated in a table.
Before creating a trigger, let’s first create sample tables for examples. Let’s create a table “tblEmployee” to keep employee personnel information and a table “tblEmployeeHistory” to contain each modified record.
SQL Server Script To Create “tblEmployee” Table
-- Creating a new table "tblEmployee" CREATE TABLE tblEmployee ( [Id] INT PRIMARY KEY, [Name] NVARCHAR(30), [Gender] VARCHAR(10), [City] VARCHAR(50), [DeptId] INT ) -- Inserting data into the "tblEmployee" table. INSERT INTO tblEmployee VALUES (101,'Shekh Ali','Male','Delhi', 1), (102,'Mark Adam','Male','New York', 1), (103,'Julie Folden','Female','Chicago', 2); -- SQL Script to create a table "tblEmployeeHistory" CREATE TABLE tblEmployeeHistory ( [Id] INT IDENTITY(1,1) PRIMARY KEY, [AuditData] NVARCHAR(500), [Date] DATETIME ) -- Select records from the following tables SELECT * FROM tblEmployee; SELECT * FROM tblEmployeeHistory;
After executing the SQL statements referred to above, the following tables will be created in the database.
In general, DML triggers create two special (virtual) magic tables called INSERTED and DELETED with the same structure or scheme as their base table.
The INSERTED table contains newly inserted records; however, the DELETED table contains old records after updating or deleting rows in a specific table.
In the SQL server trigger for the update, the temporarily inserted and deleted tables are created.
Syntax: SQL Trigger For Update Query
-- SQL script for creating a DML trigger for update events. -- Author: Shekh Ali CREATE TRIGGER TR_TblEmployee_ForUpdate ON tblEmployee FOR UPDATE AS BEGIN -- Declare variables to hold the old and updated record DECLARE @Id INT, @OldDeptId INT; DECLARE @OldName NVARCHAR(30), @OldGender NVARCHAR(10), @OldCity NVARCHAR(30); -- Variable to build the audit string DECLARE @AuditString NVARCHAR(1000); -- Select the corresponding Id from the inserted table Select Top 1 @Id = Id FROM INSERTED; -- Select the corresponding row from the deleted table SELECT @OldName = Name, @OldGender = Gender, @OldCity = City, @OldDeptId = DeptId FROM DELETED WHERE Id = @Id; -- Build the audit string dynamically Set @AuditString = 'Employee with Id = ' + Cast(@Id as NVARCHAR(4)) + ' changed'+ +' Name: ' +@OldName +' Gender: ' +' City: '+@OldCity +' DeptId: '+ Cast(@OldDeptId as NVARCHAR(4)); INSERT INTO tblEmployeeHistory VALUES(@AuditString, getdate()); END
Steps to create SQL update trigger
- First, To create a trigger, use the CREATE TRIGGER keywords, then specify the unique trigger name (Example: TR_TblEmployee_ForUpdate).
- Second, the options FOR, INSTEAD OF, or AFTER specifies when the trigger will be executed either before or after a single or multiple rows are modified.
- Then use the keyword ON to specify the name of the table associated with the trigger.
- Finally, specify the trigger body started from AS BEGIN to END which contains one or more SQL statements to be executed once trigger fired.
After execution of the above-mentioned SQL statements, a new SQL trigger for an update command will be created in the table-level trigger directory.
Please see below image for a reference.
Update record in a database table
Let’s try to update a record in the “tblEmployee” table.
-- Update query UPDATE tblEmployee SET City='Mumbai' WHERE Id=101;
Immediately after executing the UPDATE statement, the AFTER UPDATE trigger launches, and the new and old data will be stored in the INSERTED and DELETED magic tables.
Now we will able to see the updated record in the”tblEmployee” table and the old record in the “tblEmployeeHistory” table inserted by the after update trigger.
How To Create SQL Server Instead Of Update Trigger?
In SQL Server, the INSTEAD OF UPDATE Trigger is executed automatically instead of the actual UPDATE event on a table or a view.
Suppose we have an INSTEAD OF UPDATE trigger on a table “tblEmployee”.
When we attempt to update a row of the “tblEmployee” table, the following trigger will be executed automatically instead of the actual Update event.
Let’s put one condition inside the trigger, if someone tries to update the Id column from the “tblEmployee” table, then such record must not be allowed to update but raised an error message.
The update query will be only allowed to execute If any other columns are updated rather than the ID column.
Syntax: SQL Instead of update trigger
Following are the SQL statements used to create Instead of update triggers.
-- SQL script to create Instead Of Trigger. -- Author: Shekh Ali CREATE TRIGGER [dbo].[Tr_tblEmployee_InsteadOfUPDATE] ON [dbo].[tblEmployee] INSTEAD OF UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @EmployeeId INT,@DeptId INT DECLARE @Name VARCHAR(50), @City VARCHAR(50), @Gender VARCHAR(50) SELECT @EmployeeId = Id, @Name = [Name], @City = City, @Gender = Gender, @DeptId = DeptId FROM INSERTED ;-- Magic Table IF UPDATE(Id) BEGIN RAISERROR('EmployeeId cannot be updated.', 16 ,1) ROLLBACK INSERT INTO tblEmployeeHistory VALUES( 'EmployeeId ' + Cast(@EmployeeId as NVARCHAR(5)) + ' cannot be updated.',GETDATE()) END ELSE BEGIN UPDATE [tblEmployee] SET [Name] = @Name, City = @City, Gender = @Gender, DeptId = @DeptId WHERE Id = @EmployeeId END END
Let’s try to update the Id column in the table “tblEmployee”.
-- Update query UPDATE tblEmployee SET Id=105 WHERE Id=101;
The following error message will be shown when Id field is updated in tblEmployee table.
The “tblEmployeeHistory” table is also updated through the SQL Instead of Update trigger
SQL For Insert Trigger-Example
Create an INSERT trigger that will add the newly added employee Id to the History table.
-- SQL FOR INSERT TRIGGER EXAMPLE CREATE TRIGGER [dbo].[Tr_tblEmployee_INSERT] ON [dbo].[tblEmployee] FOR INSERT AS BEGIN SET NOCOUNT ON; DECLARE @EmployeeId INT SELECT @EmployeeId = INSERTED.Id FROM INSERTED INSERT INTO tblEmployeeHistory VALUES( 'EmployeeId ' + Cast(@EmployeeId as NVARCHAR(5)) + ' Inserted.',GETDATE()) END
Let’s try to insert the following employee record into the “tblEmployee” table.
INSERT INTO tblEmployee VALUES (104,'Rajat Sharma','Male','Delhi', 1);
Once we execute the above Insert statement, the trigger will insert the employee id detail in the “tblEmployeeHistory” table.
How to Create Delete Trigger In SQL Server?
Let’s Create a trigger that will not allow the Delete operation on the table “tblEmployee”.
CREATE TRIGGER Tr_tblEmployee_Delete ON tblEmployee FOR DELETE AS BEGIN PRINT 'DELETE OPERATION IS RESTRICTED.' ROLLBACK TRANSACTION END
Let’s try to DELETE the record of the employee with Id is 101 in the table “tblEmployee”.
-- Delete employee with Id 101 DELETE FROM tblEmployee WHERE ID = 101;
When we try to execute the above Delete statement, it gives us the following error.
What is trigger and its types?
A trigger in an SQL Server is a special kind of stored procedure that is triggered automatically when a given event such as Insert, Update, or Delete occurs against a table in a database.
Types of Triggers
1. Data Definition Language (DDL) triggers: CREATE, ALTER, DROP
2. Data Manipulation Language (DML) triggers: INSERT, UPDATE, DELETE
3. CLR triggers
4. and Logon triggers
What is after trigger in SQL Server?
The AFTER triggers in the SQL server are executed once the INSERT, UPDATE, or DELETE command is successfully executed on the database object.
Can triggers update views?
Yes, only by using Instead Of trigger in the view.
How do I disable a specific trigger in SQL?
ALTER TABLE TableName DISABLE TRIGGER TriggerName;
ALTER TABLE tblEmployee DISABLE TRIGGER Tr_tblEmployee_Delete;
How do I enable a specific trigger in SQL?
ALTER TABLE TableName ENABLE TRIGGER TriggerName;
ALTER TABLE tblEmployee ENABLE TRIGGER Tr_tblEmployee_Delete;
In this article, we have learned about the various types of triggers in SQL server. I hope you enjoyed this post. If you have any questions, please post your questions in the comment section.
Thanks for visiting 🙂
I am a Sr. Software engineer. I started this blog as a way to contribute back to the developer community for everything I have learned along the way from others.