Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of checking @@rowcount = 0 in a trigger?

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?

like image 808
Aleksandr Fedorenko Avatar asked Jan 17 '13 08:01

Aleksandr Fedorenko


People also ask

How to check number of rows affected by Trigger?

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.

How do I preserve the row count in a simple assignment?

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.

What is the rowcount system parameter used for?

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.

What is rowcount_big in SQL Server?

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.


2 Answers

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.

like image 165
Remus Rusanu Avatar answered Nov 15 '22 05:11

Remus Rusanu


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.

like image 33
Vishal Suthar Avatar answered Nov 15 '22 05:11

Vishal Suthar