Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

tsql - T-SQL Trigger Update

I have a table with 3 fields [ID, Name, LastUpdated].
LastUpdated has a default value of "GetDate() so it automatically fills itself when a new record is added.

When I instead run an UPDATE on TABLE, I would like to have this field reset itself to the current GetDate().

CREATE TRIGGER dbo.Table1_Updated
   ON  dbo.Table1
   AFTER UPDATE
AS 
BEGIN
    SET NOCOUNT ON;
    UPDATE dbo.Table1 SET LastUpdated = GETDATE()
END
GO

But because I don't have a WHERE Clause, ALL records get updated.

QUESTION:
Where would I get the value of the ID of the updated record on a UPDATE Trigger?

Would the fact that I'm updating a field of the table inside the Trigger, re-call a new Trigger event (and so on) ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From 'INSERTED', table INSERTED is common to both the INSERT, UPDATE trigger.

CREATE TRIGGER dbo.Table1_Updated
ON dbo.Table1
FOR INSERT, UPDATE /* Fire this trigger when a row is INSERTed or UPDATEd */
AS BEGIN
  UPDATE dbo.Table1 SET dbo.Table1.LastUpdated = GETDATE()
  FROM INSERTED
  WHERE inserted.id=Table1.id
END

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...