views:

1927

answers:

4

I am creating a stored procedure in Sql Server 2008 database. I want to return the number of rows affected. Which is a better option SET NOCOUNT OFF or RETURN @@ROWCOUNT?

ALTER PROCEDURE [dbo].[MembersActivateAccount]
    @MemberId uniqueidentifier
AS
BEGIN
    -- Should I use this?
    SET NOCOUNT OFF;

    UPDATE [dbo].Members SET accountActive = 1 WHERE id = @MemberId;
    --Or should I SET NOCOUNT ON and use the following line instead?
    --return @@ROWCOUNT;
END

I know that both work, but which is a better choice and why?


After some trying I am coming to a conclusion that SET NOCOUNT is OFF by default inside stored procedures. Is it possible to change this behavior inside my database?

+8  A: 

Use @@RowCount. It's explicit and transparent, it is entirely controlled by your code rather than a built-in behaviour.

CJM
+1. Agree with this.
TheTXI
SELECT returns a result set. SET NOCOUNT OFF returns a message. On .Net for instance the result set is a clearly in-your-face-must-deal-with-it result, as opposed to informational messages that are basically optional events raised by the connection object. Plus with @@ROWCOUNT you control *which* rowcount you want to return if your procedure has multiple results.
Remus Rusanu
+2  A: 

I know that having SET NOCOUNT ON would make a DataAdapter think there was a concurrency conflict.

You can read about it on MSDN. If the code is going to be used by DataAdapters then obviously don't use SET NOCOUNT ON.

It looks like SqlCommand also has this behaviour, which I guess is the reason why the DataAdapter has a problem (as under the hood it will use a Command object).

RichardOD
I don't see anything mentioned about SET NOCOUNT inside the SqlCommand documentation. Are you sure that there's the same problem as with DataAdapters?
niaher
RichardOD
A: 

SET ROWCOUNT 0 -- is a simple way to clear previously set count

+2  A: 

Don't use RETURN for values. By convention RETURN from stored procedures is for error codes, 0 meaning no error and non-0 meaning some kind of problem. If you need data back, the appropriate way to do it is with an OUTPUT parameter. It's a little counter-intuitive based on other languages' use of return.

onupdatecascade