Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Python Programs
    • Java Programs
    • SQL FAQ’s

AFTER INSERT Triggers in SQL Server

by suresh

The SQL Server AFTER INSERT Triggers will fire after the completion of the Insert operation. For this SQL Server After Insert trigger demo, we use the below-shown tables.

As you can see that our Employee table is Empty. Our task is to create SQL AFTER INSERT TRIGGER on this Employee table. And by using this SQL Server After Insert trigger, we want to Insert the records into Employee Table Audit, along with the audit information

After INSERT Triggers in SQL Server 1

and our Employee Table Audit is also empty

After INSERT Triggers in SQL Server 2

NOTE: SQL After Insert Triggers not Supported on Views

After INSERT Triggers in SQL Server Example

In this example, we will create an After Insert Triggers in SQL Server on the Employee table using the CREATE TRIGGER statement.

Remember, After Insert trigger 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 Employee audit table. If it fails to insert into the Employee table, then it won’t insert into the Audit table.

TIP: You can refer AFTER UPDATE TRIGGERS, TRIGGERS, and AFTER DELETE TRIGGERS articles in SQL Server.

-- Example for After INSERT Triggers in SQL Server
USE [SQL Tutorial]
GO
CREATE TRIGGER AfterINSERTTrigger on [EmployeeTable]
FOR INSERT 
AS DECLARE @EmpID INT,
	   @EmpName VARCHAR(50),
	   @EmpEducation VARCHAR(50),
	   @EmpOccupation VARCHAR(50),
	   @EmpYearlyIncome DECIMAL (10, 2), 
	   @EmpSales DECIMAL (10, 2); 

SELECT @EmpID = ins.ID FROM INSERTED ins;
SELECT @EmpName = ins.Name FROM INSERTED ins;
SELECT @EmpEducation = ins.Education FROM INSERTED ins;
SELECT @EmpOccupation = ins.Occupation FROM INSERTED ins;
SELECT @EmpYearlyIncome = ins.YearlyIncome FROM INSERTED ins;
SELECT @EmpSales = ins.Sales FROM INSERTED ins;

INSERT INTO [EmployeeTableAudit]( 
       [ID]
      ,[Name]
      ,[Education]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
      ,[ServerName]
      ,[ServerInstanceName]
      ,[Insert Time])
VALUES (@EmpID,
	@EmpName,
	@EmpEducation,
	@EmpOccupation,
	@EmpYearlyIncome,
	@EmpSales,
	CAST( SERVERPROPERTY('MachineName') AS VARCHAR(50)), 
	CAST( SERVERPROPERTY('ServerName') AS VARCHAR(50)), 
	GETDATE()
	);
PRINT 'We Successfully Fired the AFTER INSERT Triggers in SQL Server.'
GO

OUTPUT

After INSERT Triggers in SQL Server 3

ANALYSIS

First, we used the DECLARE Statement to declare the required variables

DECLARE @EmpID INT,
	@EmpName VARCHAR(50),
	@EmpEducation VARCHAR(50),
	@EmpOccupation VARCHAR(50),
	@EmpYearlyIncome DECIMAL (10, 2), 
	@EmpSales DECIMAL (10, 2);

Next, we used the SELECT Statement to select the records. The following statements will select one record from inserted values.

SELECT @EmpID = ins.ID FROM INSERTED ins;
SELECT @EmpName = ins.Name FROM INSERTED ins;
SELECT @EmpEducation = ins.Education FROM INSERTED ins;
SELECT @EmpOccupation = ins.Occupation FROM INSERTED ins;
SELECT @EmpYearlyIncome = ins.YearlyIncome FROM INSERTED ins;
SELECT @EmpSales = ins.Sales FROM INSERTED ins;

Next, we used the INSERT Statement to insert the selected values into the Employee Audit table. Here, the following statements returns the Machine Name and the server name. This information might be helpful for the audit

SERVERPROPERTY('MachineName'), 
SERVERPROPERTY('ServerName')

Let me show you the newly created SQL Server After Insert trigger. Go to the SQL Tutorial Database -> Go and expand the Employee Table -> and then expand the Triggers Folder

After INSERT Triggers in SQL Server 4

For the demonstration purpose, we are inserting five random records into the Employee table to check whether the SQL After insert Trigger is triggered or not.

INSERT INTO [EmployeeTable] (
		[Name]
	       ,[Education]
	       ,[Occupation]
	       ,[YearlyIncome]
	       ,[Sales]
	     )
VALUES ('Tutorial Gateway', 'Masters', 'Admin', 150000, 900)
      ,('Imran Khan', 'Bachelors', 'Skilled Professional', 69000, 100)
      ,('Doe Lara', 'Bachelors', 'Management', 85000, 60)
      ,('Ramesh Kumar', 'High School', 'Professional', 45000, 630)
      ,('John Ruiz', 'Partial High School', 'Clerical', 40000, 220)

OUTPUT

After INSERT Triggers in SQL Server 5

From the above screenshot, you can see that our Sql After Insert trigger is triggered, and also inserted one record into the Audit Table. Please use the following SQL Query to check the inserted records in the Employee table

SELECT [ID]
      ,[Name]
      ,[Education]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
  FROM [EmployeeTable]

OUTPUT

After INSERT Triggers in SQL Server 6

Next, check the records in the Employee table Audit using the following query.

USE [SQL Tutorial]
GO

SELECT [ID]
      ,[Name]
      ,[Education]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
      ,[ServerName]
      ,[ServerInstanceName]
      ,[Insert Time]
  FROM [EmployeeTableAudit]

OUTPUT

After INSERT Triggers in SQL Server 7

As you can see, our Audit Table is returning a single record. It is because, in our After Insert trigger definition, we are selecting only one record for each insert.

After INSERT Triggers in SQL Server Example 2

How to insert all the records into the audit table (triggered table) using the After Insert Triggers. For this, we will modify the trigger that we created in our previous example.

-- Second Example for After INSERT Triggers in SQL Server
USE [SQL Tutorial]
GO
CREATE TRIGGER AfterINSERTTriggerExample on [EmployeeTable]
FOR INSERT 
AS 
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 Our Second AFTER INSERT Triggers in SQL Server.'
GO

From the above code snippet, you can see that we are using the INSERT INTO SELECT Statement to select all the records that are inserting into the Employee table. Then we are inserting those records into the Audit table.

Next, let me insert some random records into the employee table

USE [SQL Tutorial]
GO
INSERT INTO [EmployeeTable] (
		    [Name]
		   ,[Education]
		   ,[Occupation]
		   ,[YearlyIncome]
		   ,[Sales]
	     )
VALUES ('Tutorial Gateway', 'Masters', 'Admin', 150000, 900)
      ,('Doe Lara', 'Bachelors', 'Management', 85000, 60)
      ,('Ramesh Kumar', 'High School', 'Professional', 45000, 630)
      ,('John Ruiz', 'Partial High School', 'Clerical', 40000, 220)
      ,('Imran Khan', 'Bachelors', 'Skilled Professional', 69000, 100)

OUTPUT

After INSERT Triggers in SQL Server 8

As you see, our after insert trigger has fired, and also inserted all the records into the audit table. Let us see the Emp table

After INSERT Triggers in SQL Server 9

Next, check with the Employee Audit table.

After INSERT Triggers in SQL Server 10

From the above screenshot, you can see that the After Insert trigger has inserted all the records.

Placed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW
  • C Tutorial
  • C# Tutorial
  • Java Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQL Tutorial
  • SQL Server Tutorial
  • R Tutorial
  • Power BI Tutorial
  • Tableau Tutorial
  • SSIS Tutorial
  • SSRS Tutorial
  • Informatica Tutorial
  • Talend Tutorial
  • C Programs
  • C++ Programs
  • Java Programs
  • Python Programs
  • MDX Tutorial
  • SSAS Tutorial
  • QlikView Tutorial

Copyright © 2021 | Tutorial Gateway· All Rights Reserved by Suresh

Home | About Us | Contact Us | Privacy Policy