I have a stored procedure that says
update table1 set value1 = 1 where value1 = 0 and date < getdate()
I have a trigger that goes like
CREATE TRIGGER NAME ON TABLENAME
FOR UPDATE
...
if UPDATE(value1)
BEGIN
--Some code to figure out that this trigger has been called
-- the value is always null
END
Any idea why this trigger is called even when the stored procedure does not update any values?
Read the books online article about update(), it’s actually a good read.
You can find it here, http://msdn.microsoft.com/en-us/library/ms187326.aspx.
To answer:
Update() will return true if the column is “updated,” even if no rows were affected by the update.
For example (setup):
If I run
Update TestTrigger Set Col1=0 where Col2=1and check my rows affected I’ll seeWhich we know is true, 1 is affected by the update statement, the other by the trigger.
If I run
Update TestTrigger Set Col1=0 where Col2=10I’ll see,This means that Update(Col1) is returning as true (because otherwise we’d only get a single rows affected returned).
If I run
Update TestTrigger Set Col2=0 where Col2=10I’ll seeThis is because Col1 is no longer referenced. As @Schar mentioned checking @@RowCount is a good idea as well, or alternatively you could use something like I did (linking inserted).
Kris
EDIT: and to add, from the Create Trigger BO article (http://msdn.microsoft.com/en-us/library/ms189799.aspx),