SQL Server Triggers are used to execute after or before an INSERT, DELETE, or an UPDATE operation on a table. You can use these SQL triggers on Views, or Tables to perform any of the above-specified activities. Remember, you can associate a trigger to a single table only.
Types of Triggers in SQL Server
There are two types of Triggers in SQL Server, and they are AFTER, and INSTEAD OF.
AFTER TRIGGERS in SQL Server
The after/for triggers in SQL runs after an INSERT, DELETE, or an UPDATE on a table. It means, Before it starts running, all the operations should execute, and the statement has to succeed in the constraint check as well.
- AFTER INSERT: It will fire after the completion of Insert operation on the Employee table. Once it completes inserting into the Employee table, it will start inserting into the audit table. Say, if it fails to insert into the Employee, then it won’t insert into the Audit table.
- AFTER UPDATE: This SQL Server trigger will fire after the Update operation completed on the Employees table. Once it ends Updating the Employee, it will start inserting/updating into the audit table. For instance, if it fails to update the Employees table, then it won’t insert into the Audit.
- AFTER DELETE: The After delete will fire after the completion of Delete operation on the Employee table. Once it completes deleting the records from the Employees, it will start inserting/deleting from the audit table. Say, if it fails to remove from the Employee, then it won’t insert into the Audit table
INSTEAD OF TRIGGERS in SQL Server
SQL Server Instead of Triggers fired before the execution of an INSERT, DELETE, or an UPDATE on a table start.
It means, Before the trigger starts running, it does not need any condition constraint check. So, this trigger will execute even the constraint check fails. It can further divide into
- INSTEAD OF INSERT: This instead of insert will fire before the Insert operation on Employee table starts. Once it completes inserting into the Employee Audit table, it will begin to insert into the Employee. And if it fails for some reason, it won’t insert into the Employee table.
- INSTEAD OF UPDATE: This update will fire before updating the records in the Employee table. Once it completes the execution, it will start updating the records in the Employee. And if it fails, it won’t update the table.
- INSTEAD OF DELETE: This delete will fire before deleting records from the Employee table starts. Once it executed successfully, it will begin deleting records from the Employees table. And if it fails, it won’t remove any record from the Employee.
Sql Server Triggers Syntax
The syntax of After Triggers in SQL Server is
CREATE [OR ALTER] TRIGGER [Schema_Name].Trigger_Name ON Table AFTER INSERT | UPDATE | DELETE AS BEGIN -- Statements -- Insert, Update, Or Delete Statements END
- Schema_name: Please specify the schema name. For example, dbo, or Human Resource, etc.
- Trigger_Name: You can specify any name you wish to give other than the system reserved keywords. Please try to use meaningful names so that you can identify them easily.
The basic syntax of Instead Of Triggers in SQL Server is as shown below:
CREATE [OR ALTER] TRIGGER [Schema_Name].Trigger_Name ON Table | View INSTEAD OF INSERT | UPDATE | DELETE AS BEGIN -- Trigger Statements -- Insert, Update, Or Delete Statements END
Let us see how to Create, Modify the existing one, and delete triggers in SQL Server with an example.
For the Sql Server triggers demonstration, we are working with the Employee and Employee audit table. As you can see, it is Empty
and our Audit is also empty
Create Triggers in SQL Server Example
We can create them in two ways. In this example, we show you the steps involved in creating a Trigger using the Management Studio (SSMS). Before we start generating any, let us see whether our database had any existing ones or not.
To view the existing, Please select the Database -> Expand the Table Name (on which it exists) -> Go to Triggers Folder and expand it. From the below screenshot, you can observe that our Employee table under the database has none.
Right-click on the folder will open the context menu. Please select the New Triggers.. option from it.
Once you click on that option it will open the new Query window with default Template as we have shown below
Here, you can add the Schema name, Trigger_name, TableName, Data modification statements, and the statements that you want to apply.
Create SQL Triggers using transact query
For this sql demonstration purpose, we are creating an After Insert Trigger in SQL Server to Insert the records into Employee Table Audit, along with the audit information
CREATE TRIGGER triggers_in_sql ON EmployeeTable AFTER INSERT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements here INSERT INTO [EmployeeTableAudit]( [ID] ,[Name] ,[Education] ,[Occupation] ,[YearlyIncome] ,[Sales] ,[ServerName] ,[ServerInstanceName] ,[Insert Time]) SELECT ID, Name, Education, Occupation, YearlyIncome, Sales, CAST( SERVERPROPERTY('MachineName') AS VARCHAR(50)), CAST( SERVERPROPERTY('ServerName') AS VARCHAR(50)), GETDATE() FROM INSERTED; PRINT 'We Successfully Fired the AFTER INSERT Triggers in SQL Server.' END GO
We already explained the statements inside the SQL triggers in our previous article. I suggest you refer AFTER INSERT article to under this code.
Run the above query
Messages -------- Command(s) completed successfully.
Let me show you the newly created one by opening the Object Explorer -> Go to the Database -> Go and expand the Employee -> and then expand the Folder
Let me insert 5 random records into the Employee for the demonstration purpose. It will help us to check whether the After insert is fired or not.
INSERT INTO [EmployeeTable] ( [Name] ,[Education] ,[Occupation] ,[YearlyIncome] ,[Sales] ) VALUES ('Tutorial Gateway', 'Masters Degree', 'Admin', 250000, 1900) ,('Aamir Khan', 'Bachelors', 'Skilled Professional', 69000, 100) ,('Lara Diaz', 'Bachelors', 'Management', 85000, 60) ,('Mahesh kumar', 'Degree', 'Professional', 45000, 630) ,('Ruiz John', 'Post Graduate', 'Clerical', 40000, 220)
From the above screenshot, you can see that our trigger is fired. And also, it is printing the message that we placed in it. Please use the following query to check the inserted records in the Employee.
SELECT [ID] ,[Name] ,[Education] ,[Occupation] ,[YearlyIncome] ,[Sales] FROM [EmployeeTable]
Next, check the records in the Audit table using the following query.
SELECT [ID] ,[Name] ,[Education] ,[Occupation] ,[YearlyIncome] ,[Sales] ,[ServerName] ,[ServerInstanceName] ,[Insert Time] FROM [EmployeeTableAudit]
Modify Triggers in SQL Server Example
The following examples will help you understand the steps involved in modifying the existing SQL Triggers using the Management Studio, and query.
Before we get into the SQL Trigger modification, let me show you the list of available options that the Management Studio is providing to you. As we show below, you can drop it, drop and recreate, alter it, and create it.
To modify it using the Management Studio, Please navigate to the table that holds them. Next, select the one that you want to modify (triggers_in_sql), and right-click on it will open the context menu. Here, select the Modify option
Once you choose the Modify option, a new query window will open with auto-generated ALTER TRIGGER code. You can modify it as per your requirement.
Use SQL Server Alter Trigger to Modify example
The steps involved in modifying the existing one using the ALTER statement. To do so, Click New query and return the following query.
ALTER TRIGGER [dbo].[triggers_in_sql] ON [dbo].[EmployeeTable] AFTER INSERT AS BEGIN -- Modify as per Your requirement END
Delete Triggers in SQL Server Example
The following examples will show you, How to drop, them using query, and Management Studio (SSMS). Here, we show you how to delete them using the SSMS. To delete in using the SSMS, right-click on the name that you want to delete will open the context menu. You can click on the Delete option
Here, we will show you how to delete it using the SQL Drop Trigger statement.
DROP TRIGGER [dbo].[triggers_in_sql]