Why does ExecuteNonQuery() always return -1?
Asked Answered
A

4

20

Ive used this method before to return the amount of rows changed. I am it to run an insert method, the insert runs fine in the stored procedure, but the return value from ExecuteNonQuery() always returns -1.

Here is my C# code:

int ret = 0;

using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
    using (SqlCommand cmd = new SqlCommand(QueryName, conn))
    {
        conn.Open();

        if (Params != null)
            cmd.Parameters.AddRange(Params);

        cmd.CommandType = CommandType.StoredProcedure;
        
        ret = cmd.ExecuteNonQuery();

        conn.Close();
    }
}

return ret;

Why do I get -1 instead of the actual number of rows changed?

Arrhythmia answered 14/11, 2011 at 16:49 Comment(4)
So the modifications in the table actually take place but you are getting -1?Elwina
It probably returns whatever your sproc returns, which is probably -1 if not otherwise specified..Rissole
Have you actually captured the SQL call using profiler and manually executed to see the actual changed row number?Caul
Where's the code of the stored procdure?Sinuous
D
36

From MSDN:

If you use this method to call a store procedure that perform UPDATE/INSERT in a table the method return -1 if the stored procedure has the SET NOCOUNT at ON value.

Dunham answered 14/11, 2011 at 16:52 Comment(0)
T
9

From Microsoft:

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx

You are probably getting -1 because you are using a stored procedure and not a direct table change

Teodorateodorico answered 14/11, 2011 at 16:55 Comment(0)
U
0

What value are you returning from your stored procedure? Can you show the code for your stored procedure. You probably need to edit your stored procedure to return the required value, OR, your stored procedure is returning a -1 either specifically or the variable that the stored procedure returns has -1 as its value.

Untread answered 14/11, 2011 at 17:23 Comment(0)
F
0

Get the row count output from the stored procedure something like using @rowCount=@@Rowcount. In the DAL, use dbManager.AddOutParameter("RowCount", DbType.Int32, rowCount); Then in the final rows you will get as (int)dbManager.GetParameterValue("RowCount").

Fetal answered 27/1, 2016 at 22:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.