In SQL Server 2008 R2" I am trying to insert a formula in SQL Server that will update the current value in the LastUpdatedTimestamp
field to now i.e. getdate()
every time the record is updated.
Asked
Active
Viewed 1.3k times
1

Filip De Vos
- 11,568
- 1
- 48
- 60

markpcasey
- 559
- 1
- 10
- 18
-
4There really is no question here. – taylonr Apr 21 '11 at 12:40
-
I just found I must use a trigger I was hoping that I could have used a built in function. Thanks guys – markpcasey Apr 21 '11 at 13:35
-
possible duplicate of [SQL Server 2005 Auto Updated DateTime Column - LastUpdated](http://stackoverflow.com/questions/36001/sql-server-2005-auto-updated-datetime-column-lastupdated) – Mikael Eriksson Apr 21 '11 at 13:37
1 Answers
8
You can have a default constraint on your DateTime
field that will cause the current date/time to be inserted when you insert a new row.
From there on, you need to work with a AFTER UPDATE
trigger that will update your date/time column each time the row is updated.
You cannot do this second task (updating a date/time stamp when updating the row) using a "formula" as you said - it just doesn't work that way in SQL Server.
You need to provide a trigger something along those lines:
CREATE TRIGGER trgYourTableUpdateTimestamp
ON dbo.YourTable FOR UPDATE
AS BEGIN
UPDATE
dbo.YourTable
SET
YourTimeStampColumn = GETDATE()
FROM
Inserted Ins
WHERE
dbo.YourTable.SomeUniqueId = Ins.SomeUniqueId
END

Álvaro González
- 142,137
- 41
- 261
- 360

marc_s
- 732,580
- 175
- 1,330
- 1,459