1

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?

ScArcher2
  • 82,195
  • 42
  • 116
  • 158

2 Answers2

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
  • 21,115
  • 5
  • 41
  • 45
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