//
you're reading...

SQL Triggers

Last Modified for SQL records

I use this trigger to track the last update or insert for a record.

Here’s how I create the trigger.

  • Add a “Last_Modified” column with data type “datetime” to the table.
  • Create a new SQL query in the SQL Server Management Studio.
  • Paste the following code into the SQL query.
  • CREATE TRIGGER dbo.MyTable
    ON MyTable
    FOR UPDATE,
    INSERT AS UPDATE dbo.MyTable
    SET Last_Modified = CURRENT_TIMESTAMP
    WHERE PKeyColumnName IN (SELECT PKeyColumnName FROM inserted);
    

  • Replace "dbo.MyTable" with the name of the table.
  • Replace "MyTable" with the name of the table.
  • Replace "PKeyColumnName" with the name of the primary key column for the table.
  • Execute the query.