Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Solution: ExecuteNonQuery() Always Returning -1 When Calling a Stored Procedure

0.00/5 (No votes)
19 Dec 2012 1  
A solution for ExecuteNonQuery() always returning -1 when calling a Stored Procedure

This post details another solution to a very basic problem that we face in our development and tend to miss writing Stored Procedures. We know ExecuteNonQuery() function defined in the SqlCommand class returns the number of rows affected by the query we are executing. Sometimes, when calling a Stored Procedure using the ExecuteNonquery() from .NET code returns a value of -1.

Let us consider this function that tries inserting Email address and Password fields to the database via a test SP.

Public Function TestInsert() As Boolean
Dim conn As SqlConnection = Nothing
Dim cmd As SqlCommand = Nothing
Try
    conn = New SqlConnection(connectionString)
    conn.Open()
    If passport Is Nothing Then
          cmd = New SqlCommand("sp_Test_Insert", conn)
    End If
    cmd.CommandType = CommandType.StoredProcedure
    cmd.Parameters.Add(New SqlParameter("Email", "email@email.com"))
    cmd.Parameters.Add(New SqlParameter("Password", "password"))
    Dim rows = cmd.ExecuteNonQuery()
   If rows > -1 Then
    Return True
   Else
    Return False
   End If
Catch ex As Exception
   Return False
Finally
   If Not conn Is Nothing Then
      conn.Close()
   End If
   conn = Nothing
End Try
End Function

When you generate a Stored Procedure in SSMS using the “New Stored Procedure” link, SQL generates a template for you. Below is a modified version of the same being used in our code above:

CREATE PROC sp_Test_Insert
@Email nvarchar(255),
@Password nvarchar(20)
AS
BEGIN
   SET NOCOUNT ON;
   INSERT INTO Test_Table(Email, Password) VALUES(@Email, @Password)
END

The query looks fine and after doing a bit of research, I found that the 1st line in the Stored procedure is the culprit. From MSDN, placing SET NOCOUNT ON;  in the query sets, prevent extra result sets from SQL server interfering with SELECT statements.

To resolve, just remove this line or change this line to SET NOCOUNT OFF; and everything works fine.

Hope you enjoyed reading this. Cheers!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here