I use MS SQL Server 2008 R2 I have a C# app – its client. I have met the following bug (and still cannot reproduce it. The following client code brings the “count of rows affected” more than it should:
…
DbCommand cmd = db.GetStoredProcCommand("TheStoredProc");
int numberOfAffectedRows = db.ExecuteNonQuery(cmd);
…
The stored proc TheStoredProc in the DB looks like the following:
PROCEDURE TheStoredProc
as
declare @Var1 int
**SET NOCOUNT ON;**
…
insert into [Workflows]
(
WorkflowInstanceID,
Status
)
select WorkflowInstanceID, 1
from #tmp
DROP TABLE #tmp
This is inherited code; I am not its author. But from the context I see – the Client expects the ExecuteNonQuery to bring the count of rows inserted by the “insert into [Workflows] …” operator.
And by only this operator INSERT. The proc contains one more INSERT before that one; but Client needs numberOfAffectedRows to be filled with count of only rows inserted by the “insert into [Workflows]…”.
The bug is the following: the numberOfAffectedRows got value 464. But from the DB content I see it should have been 419. And the bug is not reproducible – to the moment I saw it only once on the Productions erver; and still cannot reproduce it on my test server. On test server the numberOfAffectedRows is correct.
I have the following version: the reason of the bug is the “SET NOCOUNT ON” inb the begin of TheStoredProc. Here I have found the same problem:
… I have heard few side effects of using "SET NOCOUNT ON" a. SQLCommand.ExecuteNonQuery function returning wrong number of rows if the stored procedure has SET NOCOUNT ON. …
More often (on other forums) I met the complaint that (-1) was returned by ExecuteNonQuery in this situation.
What do you think – am I right?
The bugfix should be the following: to insert “SET NOCOUNT OFF” right before the “insert into [Workflows]…”. On my test server this works OK – but the initial code works OK too on the test server….