简体   繁体   中英

T-SQL how to create a update trigger to update a column after a row is updated?

I have a table as below. And I want to update the [UpdateTime] column automatically when a row's [Content] column is update.

CREATE TABLE [dbo].[FileContent]
(
    [FileId] INT NOT NULL PRIMARY KEY, 
    [Content] NVARCHAR(MAX) NOT NULL ,
    [UpdateTime] DATETIME NOT NULL DEFAULT GetDate()
)

What's the best way to write this Trigger?

Use this.

For more information about triggers refer this link .

CREATE TRIGGER Sample ON [dbo].[FileContent]
FOR UPDATE
AS
BEGIN
   IF UPDATE([Content])
   BEGIN
      DECLARE @nFieldID AS INT

      SELECT @nFieldID  = [FileId] FROM INSERTED

       UPDATE  [dbo].[FileContent] 
       SET [UpdateTime] = GETDATE() 
       WHERE [FileId] = @nFieldID    
   END    
END

I would use something like this:

CREATE TRIGGER yourTrigger ON [dbo].[FileContent]
INSTEAD OF UPDATE
AS

DECLARE @ID int, @newValue nvarchar(MAX)

IF UPDATE(FileId)
    RAISERROR ('Not allowed', 10,1)
ELSE
BEGIN
    IF UPDATE(Content)
    BEGIN
        --set local variables
        SET @ID = (SELECT FileId FROM inserted)
        SET @newValue = (SELECT Content FROM inserted)

        --write to table
        UPDATE [dbo].[FileContent] SET Content = @newValue, Update_Date = getdate() WHERE FileId = @ID
    END

END
GO

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM