I've read a book For eg., Pro SQL Server 2008 Relation Database Design And Implementation Lois Davidson where I've found suggestion to check the @@rowcount
inside the trigger: if it is = 0 then return
:
if @@rowcount = 0 return
I'm wondering if the no row is modified how come trigger is fired?
Trigger is fired because triggering event has occurred. Trigger does not check how many rows are affected. Therefore you've to check @@rowcount inside trigger body. To fire a trigger, triggering event is important and not the number of rows affected.
Preserve @@ROWCOUNT from the previous statement execution. Reset @@ROWCOUNT to 0 but do not return the value to the client. Statements that make a simple assignment always set the @@ROWCOUNT value to 1.
The @@rowcount system parameter indicates the number of rows affected by the LAST statement. Since you have no statements preceding the conditional 'IF' statement, it will always return zero.
Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG. To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.
The trigger fires for the statement being run. It will fire even if the table is empty, or if the statement affected no rows:
create table tr (i int);
go
create trigger g on tr after update
as
print 'foo'
go
update tr set i = 2
@Muflix Update:
create table tr (i int);
go
create trigger g on tr after insert
as
print 'foo'
go
insert into tr select * from tr;
go
As you see the trigger fires even if no rows were inserted.
Becuase Trigger
won't be able to know how many rows are affected by the triggering event that is why you have to check inside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With