Click here to Skip to main content
15,913,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
create a trigger in sql on update for taking previous row backup in another table.(like maintain the history of the record)
Posted
Comments
George Jonsson 13-Nov-15 1:33am    
What is the problem?

1 solution

Suppose you have two tables one is Employee and another is Employee_Backup.

Structure of Employee table:
SQL
CREATE TABLE Employee
(
 Emp_ID int identity,
 Emp_Name varchar(55)
);

Structure of Employee_Backup table:
SQL
CREATE TABLE Employee_Backup
(
 Emp_ID int,
 Emp_Name varchar(55)
);

Now create a trigger on table Employee table:
SQL
CREATE TRIGGER trgAfterUpdate ON dbo.Employee
FOR UPDATE
AS
DECLARE @empid int, @empname varchar(55);
SELECT @empid = i.Emp_ID FROM inserted i; 
SELECT @empname = i.Emp_Name FROM inserted i;

INSERT INTO Employee_Backup(Emp_ID,Emp_Name)
VALUES(@empid, @empname);

Execute query like below:
SQL
UPDATE Employee SET Emp_Name = 'YourName' WHERE Emp_ID = 1;

Now you can see one record will be inserted in Employee_Backup Table.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900