SQL Server 2005 自动更新日期时间列 - LastUpdated

2022-01-13 00:00:00 timestamp sql-update database sql-server

我定义了一个表(请参阅下面的代码片段).如何添加约束或其他任何内容,以便在行更改时自动更新 LastUpdate 列?

I have a table defined (see code snippet below). How can I add a constraint or whatever so that the LastUpdate column is automatically updated anytime the row is changed?

CREATE TABLE dbo.Profiles
(
        UserName                                varchar(100)            NOT NULL,
        LastUpdate                              datetime                NOT NULL  CONSTRAINT DF_Profiles_LastUpdate DEFAULT (getdate()),
        FullName                                varchar(50)             NOT NULL,
        Birthdate                               smalldatetime           NULL,
        PageSize                                int                     NOT NULL CONSTRAINT DF_Profiles_PageSize DEFAULT ((10)),
        CONSTRAINT PK_Profiles PRIMARY KEY CLUSTERED (UserName ASC),
        CONSTRAINT FK_Profils_Users FOREIGN KEY (UserName) REFERENCES dbo.Users (UserName) ON UPDATE CASCADE ON DELETE CASCADE  
)

推荐答案

默认约束只适用于插入;对于更新,请使用触发器.

A default constraint only works on inserts; for an update use a trigger.

相关文章