Sunday, 10 September 2017

After Update Trigger in SQL Server with example

In this article, I am going to explain you AFTER UPDATE Trigger in SQL-Server with example. In the previous tutorial, I have explained introduction to triggers in SQL-Server.

Related Links

AFTER Update Trigger (for update) with Example

First of all, 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.

CREATE TABLE Employee
(
EmployeeId INT PRIMARY KEY IDENTITY,
Name VARCHAR(20),
Age INT,
Gender VARCHAR(10)
)
GO
INSERT INTO Employee VALUES('Mr. A',50,'Male')
INSERT INTO Employee VALUES('Mr. B',55,'Male')
INSERT INTO Employee VALUES('Mr. C',60,'Male')
INSERT INTO Employee VALUES('Mr. D',65,'Male')
INSERT INTO Employee VALUES('Mr. E',70,'Male')
GO

Now, execute the select query to check inserted records.

SELECT * FROM Employee
EmployeeId Name Age Gender
1         Mr. A 50 Male
2         Mr. B 55 Male
3         Mr. C 60 Male
4         Mr. D 65 Male
5         Mr. E 70 Male
 

Now, we will create a Audit Table for Employee table. When somebody update record of Employee table, then we will insert same / updated record in audit table by using after update trigger. Below is the script to create Employee_Audit table.

CREATE TABLE Employee_Audit
(
Id INT IDENTITY PRIMARY KEY,
EmployeeId INT,
Name VARCHAR(20),
Age INT,
Gender VARCHAR(10),
UpdatedDate datetime
)

Creating AFTER UPDATE Trigger

Now, we will create after update trigger. Below is the script to create after update trigger.

CREATE TRIGGER tr_Employee_AfterUpdate
 
ON Employee    -- table name 
 
after UPDATE   --(you can also use 'for update')
 
AS
BEGIN
     DECLARE @EmployeeId INT,
             @Name VARCHAR(20),
             @Age INT,
             @Gender VARCHAR(20)
 
     SELECT @EmployeeId=i.EmployeeId,
            @Name=i.Name,
            @Age=i.Age,
            @Gender=i.Gender 
            FROM inserted AS i
 
       INSERT INTO Employee_Audit VALUES(@EmployeeId,@Name,@Age,@Gender,GETDATE())  
END

When you update record of Employee table then SQL-Server creates a magic table named as 'inserted' and same copy of record will we inserted into this magic table. Inserted table is accessible inside the context of trigger. You can not access inserted table outside of triggers.

Executing Update Trigger

As we can not execute triggers explicitly, to execute trigger, we need to update an employee as shown below. Here update Name column whose employeeid is 1.

UPDATE Employee SET Name ='Mr. Z' WHERE employeeid=1

As you can see below a record will be updated for Employee table and a new will be inserted for Employee_Audit table.

SELECT * FROM Employee
SELECT * FROM Employee_Audit
EmployeeId Name Age Gender
1         Mr. Z 50 Male
2         Mr. B 55 Male
3         Mr. C 60 Male
4         Mr. D 65 Male
5         Mr. E 70 Male
 
Id EmployeeId Name Age Gender UpdatedDate
1 1         Mr. Z 50 Male 2017-09-10 20:21:45.030

As you can see from above trigger, a record will be inserted in audit table whether a single column or multiple column or no column in updated. Here employee with id is 10 is not present in Employee table. Execute below script to update with employee whose id 10. Here NULL be inserted in Employee_Audit table irrespective of column is updated or not.

UPDATE Employee SET age =100 WHERE employeeid=10
GO
SELECT * FROM Employee_Audit
--Result:
Id EmployeeId Name Age  Gender UpdatedDate
1 1         Mr. Z 50  Male 2017-09-10 20:21:45.030
2 NULL         NULL NULL     NULL 2017-09-10 20:32:31.987

Now to stop above situation from happening we can count no of record for INSERTED table.

ALTER TRIGGER tr_Employee_AfterUpdate
ON Employee    -- table name 
after UPDATE   --(you can also use 'for update')
AS
BEGIN
 DECLARE @EmployeeId INT,
         @Name VARCHAR(20),
         @Age INT,
         @Gender VARCHAR(20)
 
 SELECT @EmployeeId=i.EmployeeId,
        @Name=i.Name,
        @Age=i.Age,
        @Gender=i.Gender 
        FROM inserted AS i
 
 
 DECLARE @inscnt INT; -- INSERTED row count
 SELECT @inscnt = COUNT(*) FROM INSERTED;
 IF @inscnt > 0
 BEGIN
 INSERT INTO Employee_Audit VALUES(@EmployeeId,@Name,@Age,@Gender,GETDATE()) 
 END
END

Now we can also check for specific column using UPDATE() function. If specific column is updated then only insert record into audit table.

ALTER TRIGGER tr_Employee_AfterUpdate
ON Employee    -- table name 
after UPDATE   --(you can also use 'for update')
AS
BEGIN
 DECLARE @EmployeeId INT,
         @Name VARCHAR(20),
         @Age INT,
         @Gender VARCHAR(20)
 
 SELECT @EmployeeId=i.EmployeeId,
        @Name=i.Name,
        @Age=i.Age,
        @Gender=i.Gender 
        FROM inserted AS i
 
 DECLARE @inscnt INT; -- INSERTED row count
 SELECT @inscnt = COUNT(*) FROM INSERTED;
 IF @inscnt > 0
 BEGIN
  IF UPDATE(Name) --check for updated column
  BEGIN
   INSERT INTO Employee_Audit VALUES(@EmployeeId,@Name,@Age,@Gender,GETDATE())
  END
 END
END

Now we can also check for multiple column is updated.

Using UPDATE() function

IF (UPDATE(Name) OR UPDATE(age))
BEGIN
 INSERT INTO Employee_Audit VALUES(@EmployeeId,@Name,@Age,@Gender,GETDATE()) 
END 
--OR
IF (UPDATE(Name) AND UPDATE(age))
BEGIN
 INSERT INTO Employee_Audit VALUES(@EmployeeId,@Name,@Age,@Gender,GETDATE()) 
END

Using COLUMNS_UPDATED() function

ALTER TRIGGER tr_Employee_AfterUpdate
ON Employee
after UPDATE
AS
BEGIN
 DECLARE @EmployeeId INT,
         @Name VARCHAR(20),
         @Age INT,
         @Gender VARCHAR(20)
 
 SELECT @EmployeeId=i.EmployeeId,
        @Name=i.Name,
        @Age=i.Age,
        @Gender=i.Gender 
        FROM inserted AS i
 
/*
Check whether columns 2, 3 or 4 have been column updated. If any or all  
columns 2, 3 or 4 have been changed, then insert into audit column.
Thebitmask is: 
power(2,(2-1)) + power(2,(3-1)) + power(2,(4-1)) = 14
 
Use IF (COLUMNS_UPDATED() & 14) > 0   -- for any or all (2, 3 or 4 columns is updated)
 
Use IF (COLUMNS_UPDATED() & 14) = 14 -- for all column (2, 3, and 4 columns are updated)
 
*/
 
 DECLARE @inscnt INT; -- INSERTED row count
 SELECT @inscnt = COUNT(*) FROM INSERTED;
 IF @inscnt > 0
 BEGIN
   IF (COLUMNS_UPDATED() & 14) > 0   --check if any/all  column is updated
  BEGIN
   INSERT INTO Employee_Audit VALUES(@EmployeeId,@Name,@Age,@Gender,GETDATE())
  END
 
  /*
  IF (COLUMNS_UPDATED() & 14) = 14   --check if all columns are updated
  begin
   insert into Employee_Audit values(@EmployeeId,@Name,@Age,@Gender,GETDATE())
  end
  */
 
 END
 
END
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON