更新时间:2023-09-23 11:03:58
要知道最后更新的是哪一行,需要新建一个DATETIME
/DATETIME2
类型的列> 并使用触发器对其进行更新.没有一种数据类型会在每次更新行时自动使用日期/时间信息进行自我更新.
To know which row was last updated, you need to create a new column of type DATETIME
/DATETIME2
and update it with a trigger. There is no data type that automatically updates itself with date/time information every time the row is updated.
为避免递归,您可以在触发器中使用 UPDATE()
子句,例如
To avoid recursion you can use the UPDATE()
clause inside the trigger, e.g.
ALTER TRIGGER dbo.SetLastUpdatedBusiness
ON dbo.Businesses
AFTER UPDATE -- not insert!
AS
BEGIN
IF NOT UPDATE(LastUpdated)
BEGIN
UPDATE t
SET t.LastUpdated = CURRENT_TIMESTAMP -- not dbo.LastUpdated!
FROM dbo.Businesses AS t -- not b!
INNER JOIN inserted AS i
ON t.ID = i.ID;
END
END
GO
在现代版本中,您可以使用临时表欺骗 SQL Server:
In modern versions you can trick SQL Server into doing this using temporal tables:
但这充满了警告和限制,实际上只是在忽略其他多个类似的帖子:
But this is full of caveats and limitations and was really only making light of multiple other similar posts: