Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

tsql - SQL Server automatic update datetimestamp field

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...