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
    • Go Programs
    • Python Programs
    • Java Programs

INSTEAD of UPDATE Triggers in SQL Server

by suresh

The SQL INSTEAD OF UPDATE trigger will fire before the execution starts. So, you can use this SQL Server INSTEAD OF UPDATE trigger to pass the value for Identity Columns or Updating different tables, etc.

For this SQL INSTEAD OF UPDATE trigger demonstration, we are going to use the tables that we have shown below. Here, our task is to create an SQL Server INSTEAD OF UPDATE TRIGGER on this Employee table. And by using this Instead of UPDATE Trigger, we want to restrict the records Update

Instead Of UPDATE Triggers in SQL Server 1

And our Employee Table Audit also holds the same 14 records, along with the Server name, Server Instance name, and Insert Time (Audit Information).

Instead Of UPDATE Triggers in SQL Server 2

Instead Of UPDATE Triggers in SQL Server Example

SQL Instead of Update Triggers can create on Tables, and Views. In general, we use these triggers on Views. In this example, we will show how to create an Instead of update Triggers in SQL Server. For instance, if you want to restrict the users from updating the records in the original table. And you want those updated logs in another historical table, use this trigger.

TIP: You can refer Views, TRIGGERS, INSTEAD OF INSERT TRIGGERS, and INSTEAD OF DELETE TRIGGERS articles in SQL Server.

Here, we will create an Instead of UPDATE Triggers in SQL Server on the Employee table using the CREATE TRIGGER statement. From the below 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.

It means, when the user updates any Employee table record, then the trigger will insert those records into an audit table, and kept the Employee table unchanged.

-- Example for INSTEAD OF UPDATE Triggers in SQL Server
USE [SQL Tutorial]
GO
CREATE TRIGGER InsteadOfUPDATETriggerExample on [EmployeeTable]
INSTEAD OF UPDATE 
AS DECLARE @ActionPeformed VARCHAR(50)

IF UPDATE(YearlyIncome)
BEGIN
     SET @ActionPeformed = 'Updated Yearly Income'
END
ELSE BEGIN
      SET @ActionPeformed = 'Updated Sales'
END

INSERT INTO [EmployeeTableAudit]( 
       [ID]
      ,[Name]
      ,[Education]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
      ,[Update Time]
     ,[ActionPerformed])
SELECT ID,
	Name,
	Education,
	Occupation,
	YearlyIncome,
	Sales,
	GETDATE(),
	@ActionPeformed
FROM INSERTED;
PRINT 'We Successfully Fired Our First INSTEAD OF UPDATE Triggers in SQL Server.'
GO
Instead Of UPDATE Triggers in SQL Server 3

Let me show you the newly created trigger by opening the Object Explorer -> Go to the SQL Tutorial Database -> Go and expand the Employee Table -> and then expand the Triggers Folder

Instead Of UPDATE Triggers in SQL Server 4

For the demo purpose, we are updating the Yearly Income as 123,456, and Sales = 5000 for all the records in the Employee table whose Occupation = Professional.

-- SQL INSTEAD OF UPDATE Triggers Example
USE [SQL Tutorial]
GO
UPDATE [EmployeeTable]
	SET [YearlyIncome] = 123456, [Sales] = 5000
	WHERE [Occupation] = N'Professional'
Instead Of UPDATE Triggers in SQL Server 5

From the above screenshot, you can see that our trigger is triggered. And, instead of inserting 4 records into the Employee Audit table. Please use the following SQL Query to check the inserted records in the Employee table

-- SQL INSTEAD OF UPDATE Triggers Example
USE [SQL Tutorial]
GO
SELECT [ID]
      ,[Name]
      ,[Education]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
  FROM [EmployeeTable]
Instead Of UPDATE Triggers in SQL Server 6

Though we updated the Employee table, As you can see from the above screenshot, our Employee table is unchanged. Next, check the records in the Employee table Audit using the following query.

-- SQL Server INSTEAD OF UPDATE Triggers Example
USE [SQL Tutorial]
GO

SELECT [Name]
      ,[Education]
      ,[Occupation]
      ,[YearlyIncome]
      ,[Sales]
      ,[ServerName]
      ,[ServerInstanceName]
      ,[Insert Time]
  FROM [EmployeeTableAudit]
Instead Of UPDATE Triggers in SQL Server 7

Here, you can see that the trigger has interested 4 new records into Employee audit table

Instead of UPDATE Triggers in SQL Server Example 2

Let us see how to Update all the records in the audit table (triggered table) using the Instead of Update Triggers in SQL Server. For this SQL Server Instead of UPDATE Triggers example, we are using the MERGE Statement.

-- Example for INSTEAD OF UPDATE Triggers in SQL Server
USE [SQL Tutorial]
GO
CREATE TRIGGER InsteadOfUPDATETriggerExample on [EmployeeTable]
INSTEAD OF UPDATE 
AS DECLARE @ActionPeformed VARCHAR(50)

IF UPDATE(YearlyIncome)
BEGIN
     SET @ActionPeformed = 'Updated Yearly Income'
END
ELSE BEGIN
      SET @ActionPeformed = 'Updated Sales'
END

MERGE [EmployeeTableAudit] AS AuditTab
USING (SELECT * FROM INSERTED) AS Emp
ON AuditTab.ID = emp.ID
WHEN MATCHED THEN
UPDATE SET AuditTab.[Name] = Emp.Name, 
         AuditTab.[Education] = Emp.Education, 
	 AuditTab.[Occupation] = Emp.Occupation,
	 AuditTab.[YearlyIncome] = Emp.YearlyIncome, 
	 AuditTab.[Sales] = Emp.Sales, 
	 AuditTab.[Update Time] = GETDATE(), 
	 AuditTab.[ActionPerformed] = @ActionPeformed;
PRINT 'We Successfully Fired Our Second INSTEAD OF UPDATE Triggers in SQL Server.'
GO
Instead Of UPDATE Triggers in SQL Server 8

Next, let me perform updating on the employee table

-- SQL INSTEAD OF UPDATE Triggers Example
USE [SQL Tutorial]
GO
UPDATE [EmployeeTable]
	SET [YearlyIncome] = 111111, 
	    [Sales] = 7777
	WHERE [Occupation] = N'Clerical'
Instead Of UPDATE Triggers in SQL Server 9

We don’t have to check the Employee table as we all know that there will be no updates happened in that table. Next, check with the Employee Audit table.

Instead Of UPDATE Triggers in SQL Server 10

From the above screenshot, you can see that the trigger has updated all the records.

Instead of UPDATE Triggers in SQL Server Example 3

This example shows you how to update all the rows in the Employee table using the Instead Of Update Triggers in SQL Server. For this, we are using the INNER JOIN.

-- Example for INSTEAD OF UPDATE Triggers in SQL Server
USE [SQL Tutorial]
GO
CREATE TRIGGER InsteadOfUPDATETriggerExample on [EmployeeTable]
INSTEAD OF UPDATE 
AS 

UPDATE [EmployeeTable] 
 SET [EmployeeTable].[Name] = 'Tutorial Gateway', 
     [EmployeeTable].[Education] = ins.Education,
     [EmployeeTable].[Occupation] = ins.Occupation,
     [EmployeeTable].[YearlyIncome] = ins.YearlyIncome,
     [EmployeeTable].[Sales] = 55555
 FROM [EmployeeTable] 
 INNER JOIN INSERTED AS ins
 ON [EmployeeTable].ID = ins.ID 

PRINT 'We Successfully Fired Our Third INSTEAD OF UPDATE Triggers in SQL Server.'
GO
Instead Of UPDATE Triggers in SQL Server 11

Below statement will set the name as ‘Tutorial gateway’

SET [EmployeeTable].[Name] = 'Tutorial Gateway',

Next statement will set the Sales amount as 55,555

 [EmployeeTable].[Sales] = 55555

It means, whatever you pass the values to the name, and Sales columns, Instead of Update Trigger in Sql Server will insert the ‘Tutorial gateway’, and 55,555. Or you can say, the trigger will override the values

Next, let me perform updating on the employee table

USE [SQL Tutorial]
GO
UPDATE [EmployeeTable]
	SET [YearlyIncome] = 999999, 
	    [Sales] = 88886
	WHERE [Occupation] = N'Management'
Instead Of UPDATE Triggers in SQL Server 12

From the above screenshot, our SQL instead of update trigger fired. And also updated all the rows in the employee table. Let us see the Employee table.

Instead Of UPDATE Triggers in SQL Server 13

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

Copyright © 2021· All Rights Reserved.
About | Contact | Privacy Policy