0

I have the following code to return an id number from a database. It works fine when I run it locally, but when I put the files onto the server, while it does log the data into the DB, but it only returns a 0 and not the ID number.

HHID is an ID that autoincrements when I log the info to the DB.

SqlConnection conn = new SqlConnection("DB connection stuff");
SqlCommand cmd = conn.CreateCommand();
SqlDataReader reader;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insert_workshop_requests";
cmd.Parameters.AddWithValue("@HHID", 1);
cmd.Parameters.AddWithValue("@username", usernameData.Text);
cmd.Parameters.AddWithValue("@name", nameData.Text);
cmd.Parameters.AddWithValue("@email", emailData.Text);

cmd.Parameters["@HHID"].Direction = System.Data.ParameterDirection.Output;

try
{
    conn.Open();
    reader = cmd.ExecuteReader();
    HHID = System.Convert.ToInt32(cmd.Parameters["@HHID"].Value);
}
catch (Exception exc)
{

}
finally
{
    if (conn.State != ConnectionState.Closed)
        conn.Close();
}

This is driving me crazy! Hoping someone can help, because while I've found loads of useful articles about SP that store a 0 rather than an ID, the issues are always when running locally as well. Mine working locally is making it very difficult to debug!

Thanks!

Ian
  • 30,182
  • 19
  • 69
  • 107
hlh3406
  • 1,382
  • 5
  • 29
  • 46
  • Can you share the code for the SP? – NP3 May 10 '17 at 09:41
  • How does your stored procedure look like? How do you check that it returns 0 instead of your desired Id number? – Ian May 10 '17 at 09:41
  • @hlh3406 Also, I think you should use ExecuteNonQuery – NP3 May 10 '17 at 09:44
  • By "locally" do you mean both the app and the database are local? If so I think you stored procedure is different on the server and does not set the output variable. – Crowcoder May 10 '17 at 09:50

2 Answers2

1

You are using ExecuteReader for something that is not a SELECT. This has an interesting side effect on return parameters. Until you close the reader the values inside parameters of Direction = Output are not available.

SQL OUTPUT Stored Procedures not working with ExecuteReader

So you could close the reader, but really you should use ExecuteNonQuery for INSERT/UPDATE/DELETE queries

conn.Open();
reader = cmd.ExecuteReader();
reader.Close();
HHID = System.Convert.ToInt32(cmd.Parameters["@HHID"].Value);

or better

conn.Open();
int records = cmd.ExecuteNonQuery();
HHID = System.Convert.ToInt32(cmd.Parameters["@HHID"].Value);
Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
0

as far as i can understand, you are trying to return the id of the last entry, for that you can use this and bind the result to a variable and return it

SELECT SCOPE_IDENTITY()

i hope this will work out

Chetan Talwar
  • 111
  • 1
  • 6