you can use a trigger for that
But I would also store the date of the event, and the kind of event (insert, update or delete)
Here is an example to get you started
CREATE trigger tr_UID_MedicalAllowance on dbo.MedicalAllowance
after update, insert, delete
as
begin
set nocount on
declare @Insert bit = 0
declare @Update bit = 0
declare @Delete bit = 0
--find out why we where triggered
if (exists(select 1 from inserted)) and (exists(select 1 from deleted))
set @Update = 1
else if (exists(select 1 from inserted))
set @Insert = 1
else if (exists (select 1 from deleted))
set @Delete = 1
if @Update = 1
begin
insert into MedicalAllowanceHistory (
MedicalAllowanceID,
HistoryDate,
HistoryEvent,
other columns...)
select i.MedicalAllowanceID,
getdate(),
'UPDATED',
i.other columns...
from inserted i
end
if @Insert = 1
begin
insert into MedicalAllowanceHistory (
MedicalAllowanceID,
HistoryDate,
HistoryEvent,
other columns...)
select i.MedicalAllowanceID,
getdate(),
'INSERTED',
i.other columns...
from inserted i
end
if @Delete = 1
begin
insert into MedicalAllowanceHistory (
MedicalAllowanceID,
HistoryDate,
HistoryEvent,
other columns...)
select d.MedicalAllowanceID,
getdate(),
'DELETED',
d.other columns...
from deleted d
end
end
It is also possible to store old and new values in case of update, the new values are in the inserted
table and the old are in the deleted
table.
In that case the update
part could look something like this
if @Update = 1
begin
insert into MedicalAllowanceHistory (
MedicalAllowanceID,
HistoryDate,
HistoryEvent,
NewLimit,
OldLimit,
other columns...)
select i.MedicalAllowanceID,
getdate(),
'UPDATED',
i.Limit,
d.Limit,
other columns...
from inserted i
inner join deleted d on i.MedicalAllowanceID = d.MedicalAllowanceID
end