1 Replies - 134 Views - Last Post: 03 February 2012 - 09:16 AM Rate Topic: -----

Topic Sponsor:

#1 scolty  Icon User is offline

  • D.I.C Regular

Reputation: 2
  • View blog
  • Posts: 259
  • Joined: 27-April 11

Stored Procedure not returning correct value

Posted 03 February 2012 - 08:34 AM

Hi, I cant get the following stored procedure to return the correct value.

[sql code]
create procedure numberofrows
as

declare @counter float

set @counter = (select count(*) from testtable2)

return @counter



[c# code]
...
            SqlConnection cn = new SqlConnection(connectionString);
            cn.Open();
            MessageBox.Show("connection made");
            SqlCommand storProc = new SqlCommand("numberofrows", cn);
            storProc.CommandType = CommandType.StoredProcedure;
            double result = storProc.ExecuteNonQuery();

            textBox1.Text = result.ToString();
...



i believe ExecuteNonQuery() is the issue but i dont know what to replace it with.

Any help would be appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: Stored Procedure not returning correct value

#2 Curtis Rutland  Icon User is online

  • (╯°□°)╯︵ (~ .o.)~
  • member icon

Reputation: 3134
  • View blog
  • Posts: 5,402
  • Joined: 08-June 10

Re: Stored Procedure not returning correct value

Posted 03 February 2012 - 09:16 AM

*
POPULAR

Well, first of all, ExecuteNonQuery returns the number of affected rows. In this case, there are none. It's not even a query that can affect rows.

I'd suggest modifying your SP in one of two ways. First, simply perform the select statement. I'm using my own table name here:

CREATE PROCEDURE spNumberOfRowsSelect
AS
BEGIN
	SET NOCOUNT ON;

    select count(*) as [Count] from verb
END
GO



And use ExecuteScalar instead of ExecuteNonQuery. Note that ExecuteScalar returns an Object, so it must be cast to an int for this.

You can also use Output parameters:

CREATE PROCEDURE spNumberOfRowsOut @count int output
AS
BEGIN
	SET NOCOUNT ON;

    select @count = count(*) from Verb
END
GO


In this case, you'd have to do something like this:

var conn = new SqlConnection(connStr);
var cmd = new SqlCommand("spNumberOfRowsOut", conn) {CommandType = CommandType.StoredProcedure};
var param = new SqlParameter("@count", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(param);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine(cmd.Parameters["@count"].Value);


Was This Post Helpful? 5
  • +
  • -

Page 1 of 1