How to get old value and new value of multiple field in trigger in SQL server?

3.7k views Asked by At

I have a table Person:

CREATE TABLE Person
(
    ID INT PRIMARY KEY,
    FirstName varchar(50),
    LastName varchar(50),
    Phone varchar(50),
    Address varchar(50),
    City varchar(50),
    PinCode varchar(50),
    DateOfBirth DATETIME,
    UpdatedOn DATETIME,
    UpdatedBy varchar(50)
)

Whenever I insert or update the multiple fields from above table then I want previous value and current value of all updated fields and store that in another table using Trigger. How we can get values of all updated fields.

For example

INSERT INTO Person 
VALUES (1, 'first', 'last', '11111', 'add', 'city', 'pin', GETDATE(), GETDATE(), 'ABC')

UPDATE Person
SET FirstName = 'First11', 
    LastName = 'Last22', 
    Phone = '1010101010'
WHERE id = 1

When I will hit above commands in both cases I want old and current value and store it in another table. How we can achieve this using triggers?

1

There are 1 answers

0
rachidait On

For SQL Server when you updated ( he delete the old values and then insert the new values )

   ALTER TRIGGER [dbo].[YOUR_TRIGGER_NAME_INSERT]
   ON  [dbo].[YOUR_TABLE] 
   AFTER INSERT --Here when you insered rows
   AS 
   BEGIN
        select * from inserted --get all inserted rows  
        --Your code
   END

And Update

   ALTER TRIGGER [dbo].[YOUR_TRIGGER_NAME_UPDATE] 
   ON  [dbo].[YOUR_TABLE] 
   AFTER UPDATE--Here when you updated rows
   AS 
   BEGIN
        select * from inserted --get all inserted (new values) rows 
        select * from deleted--get all deleted (old values) rows    
        --Your code
   END