Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - is using @@ROWCOUNT safe in multithreaded applications?

I am using SQL Server 2008.

I have a table A which accepts many insert/update in one seconds. After insert, update I want to get the number of rows affected.

INSERT INTO A (ID) VALUES (1)
IF @@ROWCOUNT = 0
    PRINT 'NO ROWS AFFECTED'

While query is being executed, the same query may be called again by application. So what happens if the current execution is after INSERT but before IF block at that moment.

Do you think @@ROWCOUNT may give wrong result for that reason?

Or is it always safe in its context?

like image 851
Ahmet Altun Avatar asked Jan 22 '12 10:01

Ahmet Altun


People also ask

Is Rowcount thread safe?

All replies. Both are thread safe function.

What is the use of @@ rowcount in SQL Server?

SQL Server @@ROWCOUNT is a system variable that is used to return the number of rows that are affected by the last executed statement in the batch.

How does SQL Rowcount work?

%ROWCOUNT yields the number of rows affected by an INSERT , UPDATE , or DELETE statement, or returned by a SELECT INTO statement. %ROWCOUNT yields 0 if an INSERT , UPDATE , or DELETE statement affected no rows, or a SELECT INTO statement returned no rows.


2 Answers

Yes - its safe. It always refers the previous operation in current query

BUT

if you want to know the number of rows affected, save it to variable first, because after IF statement the count @@ROWCOUNT resets

INSERT INTO A (ID) VALUES (1)
DECLARE @rc INT = @@ROWCOUNT
IF @rc = 0
    PRINT 'NO ROWS AFFECTED'
ELSE
  SELECT @rc AS RowsAffected
like image 114
Oleg Dok Avatar answered Sep 28 '22 11:09

Oleg Dok


@@ROWCOUNT is both scope and connection safe.

In fact, it reads only the last statement row count for that connection and scope. The full rules are here on MSDN (cursors, DML, EXECUTE etc)

To use it in subsequent statements, you need to store it in a local variable.

like image 27
gbn Avatar answered Sep 28 '22 12:09

gbn