I have a simple table as below.
I want to create a trigger to insert new values into "SectionsAudit" Table.
Means:
- If a new row is inserted into the
Sectionstable, I want to insert the same row into theAudittable - If an existing row is updated in the
Sectionstable, I want to create a new row in theAudittable with the updated row.
How can I do that in SQL Server? Also, I would like to know if this a good practice?
CREATE TABLE [dbo].[Sections]
(
[Id] int IDENTITY(1,1) NOT NULL,
[Name] varchar(25) NOT NULL,
[InsertedBy] varchar(25) NOT NULL,
[InsertedDateTime] datetime NOT NULL,
[UpdatedBy] varchar(25) NOT NULL,
[UpdatedDateTime] datetime NOT NULL,
CONSTRAINT [PK_Id] PRIMARY KEY CLUSTERED([Id])
)


The trigger will look something like this, its a good practice depending of the MS SQL version you're using. Note that for using this approach is necessary to have in your dbo.SectionsAudit a field to track the ModificationId of the original Record (in the example I called it IdModi)