How to: Create trigger for auto update modified date with SQL Server 2008

Sql ServerSql Server-2008DateTriggers

Sql Server Problem Overview


It would be nice to know how to create a trigger that auto-updates the modifiedDate column in my SQL Server table:

Table TimeEntry

Id (PK)
UserId (FK)
Description
Time
GenDate
ModDate

Trigger code:

+   TR_TimeEntry_UpdateModDate()
+   TR_TimeEntry_InsertGenDate()

An example for update ModDate would be nice.

Sql Server Solutions


Solution 1 - Sql Server

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJulianView Question on Stackoverflow
Solution 1 - Sql Servermarc_sView Answer on Stackoverflow