Sql server on update set current timestamp

2020-02-05 10:19发布

I need a timestamp field which updates every time the user modifies the record.

So far I used MySql in which I can even use this in the field creation:

Alter table myTable add `last_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP **ON UPDATE CURRENT_TIMESTAMP**

I couldn't find this possibility in Sql Server.

Then I tried writing a trigger.

In a MySql trigger this is simple :

Set new.last_time=CURRENT_TIMESTAMP();

Sql Server doesn't seem to know neither new, nor old syntax, it gave me error on compilation.

the:

update myTable set last_time =CURRENT_TIMESTAMP;

worked, but it updated all the rows instead of the current.

Isn't there a way the tell Sql Server to update the current record? Should I user "update where myid=something" ?

Doesn't SQL Server know which is the actual record it is processing?

标签: sql-server
2条回答
ら.Afraid
2楼-- · 2020-02-05 10:54

Use rowversion datatype. Rowversion is generally used as a mechanism for version-stamping table rows in MS-SQL server. The rowversion data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime2 data type. For more information please read about rowversion in msdn (http://technet.microsoft.com/en-us/library/ms182776.aspx)

查看更多
够拽才男人
3楼-- · 2020-02-05 10:58

And if you really need a timestamp - then make a trigger on insert and update that updates the column with the current timestmap.

CREATE TRIGGER dbo.trgAfterUpdate ON dbo.YourTable
AFTER INSERT, UPDATE 
AS
  UPDATE dbo.YourTable
  SET last_changed = GETDATE()
  FROM Inserted i

To update a single row (which has been edited or inserted) you should use

CREATE TRIGGER dbo.trgAfterUpdate ON dbo.YourTable
AFTER INSERT, UPDATE 
AS
  UPDATE f set LastUpdate=GETDATE() 
  FROM 
  dbo.[YourTable] AS f 
  INNER JOIN inserted 
  AS i 
  ON f.rowID = i.rowID;

These should be all you need. GETUTCDATE() if you want it in UTC (which I prefer)

SQL Server absolutely knows the rows it processes

update myTable set last_time =CURRENT_TIMESTAMP ; worked, but it updated all the rows instead of the current.

Yeah, guess what - because that is exactly what you tell SQL Server: Update all rows in the table.

Doesn't Sql Server know which is the actual record it is processing?

Sets have no current row ;) That is where the problem starts.

The only way to do that exactly as you want is up in my answer on the beginning: a timestamp. Due to the misconceptions, though, I add an advice: get a book about SQL basics.

查看更多
登录 后发表回答