Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a datetime column in SQL Server that automatically updates when the record is modified

I need to create a new DATETIME column in SQL Server that will always contain the date of when the record was created, and then it needs to automatically update whenever the record is modified. I've heard people say I need a trigger, which is fine, but I don't know how to write it. Could somebody help with the syntax for a trigger to accomplish this?

In MySQL terms, it should do exactly the same as this MySQL statement:

ADD `modstamp` timestamp NULL      DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP 

Here are a few requirements:

  • I can't alter my UPDATE statements to set the field when the row is modified, because I don't control the application logic that writes to the records.
  • Ideally, I would not need to know the names of any other columns in the table (such as the primary key)
  • It should be short and efficient, because it will happen very often.
like image 784
Jesse Barnum Avatar asked Feb 01 '14 01:02

Jesse Barnum


People also ask

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

You can use now() with default auto fill and current date and time for this. Later, you can extract the date part using date() function. Let us set the default value with some date.

How can I update a DateTime column in SQL?

To update with the current date and time: UPDATE table_name SET date_field = CURRENT_TIMESTAMP; To update with a specific date value: UPDATE table_name SET date_field = 'YYYY-MM-DD HH:MM:SS.

How do I add a last modified and created column in a SQL Server table?

You need to join the Inserted pseudo table which contains all rows that were updated with your base table on your primary key for that table. And you'll have to create this AFTER UPDATE trigger for each table that you want to have a modified column in.

How can I add last modified date in SQL?

Some database tables include a “last modified” column, which stores the date and time that the row was last updated. Each time the row is updated, the date is updated to reflect the date and time of that update. In SQL Server, you can use a trigger to perform this update.


1 Answers

SQL Server doesn't have a way to define a default value for UPDATE.

So you need to add a column with default value for inserting:

ADD modstamp DATETIME2 NULL DEFAULT GETDATE() 

And add a trigger on that table:

CREATE TRIGGER tgr_modstamp ON **TABLENAME** AFTER UPDATE AS   UPDATE **TABLENAME**   SET ModStamp = GETDATE()   WHERE **ID** IN (SELECT DISTINCT **ID** FROM Inserted) 

And yes, you need to specify a identity column for each trigger.

CAUTION: take care when inserting columns on tables where you don't know the code of the application. If your app have INSERT VALUES command without column definition, it will raise errors even with default value on new columns.

like image 171
rkawano Avatar answered Sep 25 '22 17:09

rkawano