Tuesday, June 22, 2010

Last Updated Field in Database

The most convenient way to populate a last updated/modified or created field in SQL Server is by writing a trigger:

USE [DatabaseName]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[LastUpdated_TableName] on [dbo].[TableName]
FOR UPDATE, INSERT AS
UPDATE dbo.CaseVoteFact
SET LastUpdatedOn = GetDate()
WHERE PrimaryKeyOfTable in (SELECT PrimaryKeyOfTable FROM inserted)


You can also used GetDate() as a default field but this will only put the date in for inserts and not for updates.

No comments:

Post a Comment