如何添加“上次更新"SQL Server 2008 R2 表中的列? [英] How do I add a "last updated" column in a SQL Server 2008 R2 table?

查看:20
本文介绍了如何添加“上次更新"SQL Server 2008 R2 表中的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 SQL Server 2008 R2 数据库中有一个表,我想添加一个名为 LastUpdated 的列,该列将在每次更新行时自动更改.这样,我就可以看到每一行的最后更新时间.

I have a table in my SQL Server 2008 R2 database, and would like to add a column called LastUpdated, that will automatically be changed every time the row is updated. That way, I can see when each individual row was last updated.

似乎 SQL Server 2008 R2 没有像早期版本那样处理这种情况的数据类型,所以我不确定最好的方法.我想知道使用触发器,但是当触发器更新行时会发生什么?这会再次触发触发器等吗?

It seems that SQL Server 2008 R2 doesn't have a data type to handle this like earlier versions did, so I'm not sure of the best way to do it. I wondered about using a trigger, but what would happen when the trigger updated the row? Will that fire the trigger again, etc?

推荐答案

要知道上次更新的是哪一行,您需要创建一个类型为 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:

这篇关于如何添加“上次更新"SQL Server 2008 R2 表中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆