如何:使用 SQL Server 2008 为自动更新修改日期创建触发器 [英] How to: Create trigger for auto update modified date with SQL Server 2008

查看:53
本文介绍了如何:使用 SQL Server 2008 为自动更新修改日期创建触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很高兴知道如何创建一个触发器来自动更新我的 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)

这篇关于如何:使用 SQL Server 2008 为自动更新修改日期创建触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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