Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 742
Julian Avatar asked Oct 12 '11 09:10

Julian


People also ask

How do I get the date to automatically update in SQL?

You can make the trigger in your create table statement with an with an on update . create table whatever ( ... updated datetime default current_timestamp on update current_timestamp ); And then there's MySQL's timestamp date type.

How do I create a trigger update in SQL?

trigger_name: This is the name of the trigger which you want to create. table_name: This is the name of the table to which the trigger will be applied. SQL statements: SQL statements form the body of the trigger. These are a set of SQL operations that will be performed once the AFTER UPDATE trigger is invoked.

What are 3 types of SQL triggers?

SQL Server has three types of triggers: DML (Data Manipulation Language) Triggers. DDL (Data Definition Language) Triggers. Logon Triggers.


1 Answers

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) 
like image 54
marc_s Avatar answered Oct 20 '22 09:10

marc_s