如何:使用 SQL Server 2008 为自动更新修改日期创建触发器

2021-12-13 00:00:00 date sql-server-2008 sql-server triggers

很高兴知道如何创建一个触发器来自动更新我的 SQL Server 表中的 modifiedDate 列:

It would be nice to know how to create a trigger that auto-updates the modifiedDate column in my SQL Server table:

表 TimeEntry

Id (PK)
UserId (FK)
Description
Time
GenDate
ModDate

触发代码:

+   TR_TimeEntry_UpdateModDate()
+   TR_TimeEntry_InsertGenDate()

更新 ModDate 的示例会很好.

An example for update ModDate would be nice.

推荐答案

我的方法:

  • ModDate 列上定义一个 默认约束,值为 GETDATE() - 这将处理 INSERT 案例

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

有一个 AFTER UPDATE 触发器来更新 ModDate

have a AFTER UPDATE trigger to update the ModDate column

类似于:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

相关文章