简体   繁体   English

在使用更新后触发器触发其他列的更新后,如何将日期列中的特定行更新为今天?

[英]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? 当使用T-SQL中的更新后触发器更新(未插入)Column CustomerProductID时,如何将Date列DateMod更新为今天的日期?

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. 一些背景信息:表已经包含产品列表(键列Itemcode ),一旦收到CustomerProductID,它将特定行(产品)的列从NULL更改为整数值。 This update is the trigger to update column DateMod to todays date for the row (product). 此更新是将行(产品)的DateMod列更新为今天的日期的触发器。 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: 我正在使用SSMS 2008,并且具有类似以下代码的内容,它更改了整个日期列,而不是更新行的特定日期字段:

 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? 我已经阅读了一些使用old.value和new.value或使用where存在的解决方案(从插入/更新中选择)的解决方案,但是它如何工作? 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). 我更喜欢将其作为before update触发器(在更新后的触发器中进行更新会提示无限循环,在某些数据库中是不允许的)。 But SQL Server doesn't support that. 但是SQL Server不支持。

In any case, the right syntax is to use inserted to join back to the original table: 无论如何,正确的语法是使用inserted联接回原始表:

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. 更改代码,使PrimaryKeyColumn是正确的主键列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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