Wednesday, March 7, 2012

Retrieve record just updated

I want to add an update trigger to keep a LastDateModified column up to date. I also want to make the trigger as generic as possible so I can cut&paste into others, the column has the same name throughtout the system. How can I retrieve the record I just updated so I can change the date? Also, if my update trigger updates a record, will this cause a loop?

In the context of a TRIGGER, there are two virtual tables, known as inserted and deleted.

To update the [LastDateModified] column, your TRIGGER action would be something like this:

Code Snippet

UPDATE MyTable

SET LastDateModified = getdate()

FROM inserted i

JOIN MyTable m
ON m.PKColumn = i.PKColumn

And no, the TRIGGER does not cause a loop.

|||The trigger "should not" cause a loop, unless recursive triggers are on in the database.|||This works perfectly except for one thing, the "architect" created several table without keys. Now, I get to go back and fix the mistakes of someone that thought they were "Super SQL Designer".

No comments:

Post a Comment