I'd like to record the insert date and an update date on a table. What is the best way to do this in SQL Server 2008?
Asked
Active
Viewed 157 times
1
-
Can you be more specific? What tables or data are you storing? SQL generally has a getdate() that retrieves the date and time. – Tyler Ferraro Apr 21 '11 at 17:33
-
best way is to push it from you data-access code (like SubSonic do) or write triggers for update and insert – TheVillageIdiot Apr 21 '11 at 17:35
-
http://stackoverflow.com/questions/5744067/sql-server-automatic-update-datetimestamp-field/5746102#5746102 – Mikael Eriksson Apr 21 '11 at 19:29
2 Answers
3
For the insert date column, you can set the column default to GETDATE()
(or GETUTCDATE()
).
For the update date, you would need to use a trigger to set the column to the current date whenever there's an update.

Rebecca Chernoff
- 22,065
- 5
- 42
- 46
3
For Insert Date you can use the following trigger:
CREATE TRIGGER INSERT_DATE ON TABLE1
FOR INSERT
AS
BEGIN
SET NOCOUNT ON
UPDATE TABLE1
SET CreatedOn = GETDATE()
FROM TABLE1 A
INNER JOIN Inserted INS ON (INS.Id = A.Id)
SET NOCOUNT OFF
END
and for Update you can use the following trigger:
CREATE TRIGGER Update ON TABLE1
FOR UPDATE
AS
BEGIN
SET NOCOUNT ON
UPDATE TABLE1
SET UpdatedOn = GETDATE()
FROM TABLE1 A
INNER JOIN Inserted INS ON (A.Id = INS.Id)
SET NOCOUNT OFF
END