I need a trigger that updates a table row field if one or more fields of that row is updated.
Suppose you have an Employees table that may look as follows:
EmployeeId Name Address ModificationDate
1 Spears 27 Sober Road
2 Jagger 65 Straight Street
If there is a real change in the value of any field except the EmployeeId and ModificationDate fields, the trigger should generate a time value and update the ModificationDate.
Example 1 of a real change:
update dbo.Employees
set Name = 'Beggar'
where EmployeeId = 2
Example 2 of no real change:
update dbo.Employees
set Name = 'Jagger'
where EmployeeId = 2
If an update in Example 2 executes, the trigger should not update the ModificationDate field.
In a trigger, you have access to the ‘inserted’ and ‘deleted’ system tables.
Those tables contains the records in the table that have been updated by the statement that caused the trigger to execute.
For an ‘UPDATE’ trigger, the ‘inserted’ table contains the records like they are in the new state, the ‘deleted’ table contains the records with the old values.
You’ll have to make use of those 2 tables to find out which records have really changed, and update the ModificationDate for those records.
I think the statement inside the trigger will look something like this. (I haven’t tested it)
Edit:
I’ve played around a bit: