-1

I have a table Employee:

CREATE TABLE [dbo].[Employee]
(
    [EmployeeCode] [int] NOT NULL,
    [FirstName] [varchar](50) NULL,
    [LastName] [varchar](50) NULL,
    [Email] [varchar](50) NULL,
    [Position] [varchar](30) NULL
)

I want to log changes in Employee_Audit table every time there's a change in Position (along with the Old Position, New Position and Timestamp) in Employee table.

CREATE TABLE [dbo].[Employee_Audit]
(
    [EmployeeCode] [int] NOT NULL,
    [FirstName] [varchar](50) NULL,
    [LastName] [varchar](50) NULL,
    [Email] [varchar](50) NULL,
    [PositionOld] [varchar](30) NULL,
    [PositionNew] [varchar](30) NULL,
    [Date] [datetime] NULL
 )

How do I achieve this?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Victor McIntyre
  • 93
  • 1
  • 10

2 Answers2

2

You basically need an UPDATE trigger that checks if the Position value has changed - and if so, records the details into Employee_Audit:

CREATE OR REPLACE trgEmployeeUpdate
ON dbo.Employee 
AFTER UPDATE 
AS
BEGIN
    -- based on the Inserted and Deleted pseudo tables, join the rows
    -- that were updated and look for changes in "Position"
    INSERT INTO dbo.Employee_Audit (EmployeeCode, FirstName, LastName, Email, 
                                    PositionOld, PositionNew, [Date])
        SELECT
            i.EmployeeCode, i.FirstName, i.LastName, i.Email,
            d.Position, i.Position, SYSDATETIME()
        FROM
            Inserted i
        INNER JOIN
            Deleted d ON i.EmployeeCode = d.EmployeeCode
        WHERE
            i.Position <> d.Position    -- Position has changed
END
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
1

In addition to trigger option @marc_s mentioned, If you want to not just consider position, and considering all column changes auditing, below options provide you to do auditing, without any specific programming need. You can see whether it fits for your needs.

Venkataraman R
  • 12,181
  • 2
  • 31
  • 58