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

时间:2022-06-21 15:10:12

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

如果知道如何创建一个触发器来自动更新我的SQL Server表中的modifiedDate列,那就太好了:

Table TimeEntry

表TimeEntry

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

Trigger code:

触发代码:

+   TR_TimeEntry_UpdateModDate()
+   TR_TimeEntry_InsertGenDate()

An example for update ModDate would be nice.

更新ModDate的一个例子会很好。

1 个解决方案

#1


75  

My approach:

我的方法:

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

    在ModDate列上定义一个默认约束,其值为GETDATE()——它处理插入情况

  • have a AFTER UPDATE trigger to update the ModDate column

    是否有一个更新后触发器来更新ModDate列

Something like:

喜欢的东西:

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

#1


75  

My approach:

我的方法:

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

    在ModDate列上定义一个默认约束,其值为GETDATE()——它处理插入情况

  • have a AFTER UPDATE trigger to update the ModDate column

    是否有一个更新后触发器来更新ModDate列

Something like:

喜欢的东西:

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