简体   繁体   中英

How to update specific row in datecolumn to date today after update on other column using after update trigger?

How to update date Column DateMod to today's date when Column CustomerProductID is updated (not inserted) using an after update trigger in T-SQL?

Some background info: Table already contains list of products (key column Itemcode ), once the CustomerProductID is received it changes the column for that particular row (product) from NULL to integer value. This update is the trigger to update column DateMod to todays date for the row (product). I am using SSMS 2008 and have something like the following code which changes the whole date column, not the particular date field for the updated row:

 CREATE TRIGGER trigger_name
   ON Table1
   AFTER UPDATE
AS 
BEGIN
      SET NOCOUNT ON;
      IF UPDATE (CustomerProductID) BEGIN
        Update Table1
        SET DateMod=GETDATE() 
      END
END

I have read some solutions using old.value and new.value or using where exists (select from inserted/updated), but how does that work? If both methods work, which one is the most beneficial in this case? Thanks a lot!

I prefer do this as a before update trigger (a logical thing . . . doing updates in after update triggers suggests infinite loops and is not allowed in some databases). But SQL Server doesn't support that.

In any case, the right syntax is to use inserted to join back to the original table:

CREATE TRIGGER trigger_name
   ON Table1
   AFTER UPDATE
AS 
BEGIN
      SET NOCOUNT ON;
      IF UPDATE(CustomerProductID) BEGIN
        Update t1
            SET DateMod = GETDATE() 
            FROM Table1 t1 join
                 Inserted i
                 ON Table1.PrimaryKeyColumn = i.PrimaryKeyColumn
      END
END

Change the code so PrimaryKeyColumn is the right primary key column.

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