views:

76

answers:

4

Is it possible to create a trigger on a field within a table being updated?

So if I have:

TableA
  Field1
  Field2
  ....

I want to update a certain value when Field1 is changed. In this instance, I want to update Field2 when Field1 is updated, but don't want to have that change cause another trigger invocation, etc...

+2  A: 

Please provide more details and ask yourself if a trigger is really needed? In my experience, triggers like this seem to become technical debt within a matter of one or two interations.

Kris Krause
Resetting a flag: when field1 is updated, field2 (the flag) needs to be reset. It would be easier to have the job that's updating field1 also reset field2, but I don't control that part of the application.
chris
So you have permission/access to update field1, but not field2... hmmm...can you add an additional column?
Kris Krause
There's a nightly job that imports data, and when it's done it updates the timestamp. I don't control that, so can't configure it to update the flag field. When it's done updating, I need to run a report on the new data, and I can reset the flag to indicate the report has been run.
chris
A: 

You can use an INSTEAD OF trigger in this case. These are NOT fired recursively. Read here for more information on recursive triggers (search for "recursively").

As always, be VERY CAREFUL what you do with an INSTEAD OF trigger. You can do some very nasty things (like when somebody calls an insert statement, you can deflect that to be a delete statement on some random record - i.e. a very nasty thing to do!).

Jaxidian
A: 

This seems to solve my problem:

CREATE TRIGGER trg_name ON TableA
AFTER UPDATE
AS 
BEGIN
IF UPDATE(FieldA) 
  update import_status set FieldB = 0
END
GO

Update:

As pointed out in the comments, this is generally a bad idea, since it would updated EVERY SINGLE ROW, which is probably not what you want. In this particular case, however, there will only ever be one row, which is just used to store the timestamp and flag field.

chris
The trigger has update permission, but your calling code does not? Correct?
Kris Krause
See the comment in your answer - I have update permissions, but that doesn't help.
chris
That's incredibly bad. Every time you update any row and modify FieldA, FieldB will be set to 0 in **all** rows.
erikkallen
You'll have to do `UPDATE import_status SET FieldB = 0 WHERE primary_key IN(SELECT primary_key FROM inserted)`
erikkallen
This table will only ever have one row - it's just tracking a timestamp for the last db-wide update. Yes, in general this is a bad idea; in this case though it does what it needs to do.
chris
A: 

You can check if Field1 value has been changed by selecting its previous value from DELETED.

SELECT @prevValue = Field1 FROM DELETED WHERE ...
kor_