tags:

views:

81

answers:

2

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?

A: 

A friend commented that I would be good with the following line in the trigger (indicating the trigger always fires)

IF @@ROWCOUNT=0 RETURN
schar
+3  A: 

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 OBJECT_ID('TestTrigger', 'U') is not null drop table TestTrigger
GO
create table TestTrigger(
  ID int identity(1,1)
, Col1 int
, Col2 int
, Trig varchar(1) default 'N' 
)
Insert into TestTrigger(Col1, Col2) values (1,1)
Insert into TestTrigger(Col1, Col2) values (1,2)
GO
IF OBJECT_ID('Testing', 'TR') is not null drop trigger Testing
GO
Create Trigger Testing on TestTrigger
For Update
as
Begin
If Update(Col1)
    begin
        Update TestTrigger Set Trig='Y' where ID=(Select ID from Inserted)
    end
End 

If I run Update TestTrigger Set Col1=0 where Col2=1 and check my rows affected I'll see

(1 row(s) affected)
(1 row(s) affected)

Which 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=10 I'll see,

(0 row(s) affected)
(0 row(s) affected)

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=10 I'll see

(0 row(s) affected)

This 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),

These triggers fire when any valid event is fired, regardless of whether or not any table rows are affected.

KSimons
oh, my example trigger has an issue... if you update more than a single row in testtrigger it will result in a sub-query returned more than 1 row (change ID= to ID in to fix)
KSimons
@KSimons Thanks for very comprehensive answer. I would check this out and respond back. Too late today ;)
schar