When one of asp.net project was in develop stage, we always got the exception ‘Must declare the scalar variable  “@variableName” ‘

I checked and searched from internet, about this issue, there have been many different reasons and solutons. But seems all of them are not fit our case.

I had to check by myself. I focused on this section of code:

           SqlConnection conn = new SqlConnection(DbConstants.ConnectionString);

             string sSql = “SELECT xSubID FROM  aTABLE ” +
                    ” WHERE cID = @variableName”;
            try
            {
                conn.Open();
              
                SqlCommand myCommand = new SqlCommand();
                myCommand.Parameters.AddWithValue(”@variableName”, contractorID);
                myCommand.Connection = conn;
                myCommand.CommandText = sSqlValidate;

                return int.Parse(myCommand.ExecuteScalar().ToString());
            }
            catch (Exception ex)
            {
                DB.AddToExceptionLog(ex);
            }
            finally
            {
                conn.Close();
            }

I tried to change to the following code:

           SqlConnection conn = new SqlConnection(DbConstants.ConnectionString);

             string sSql = “SELECT xSubID FROM  aTABLE ” +
                    ” WHERE cID = @variableName”;
            try
            {
                conn.Open();
              
//Why I changed to this just because I suppose the SQLCommandType should be given, in this case , The SQLCommandType is text, but also I suppose the following code has implidly set the SQLCommandType
                SqlCommand myCommand = new SqlCommand(sSql, conn);
                myCommand.Parameters.AddWithValue(
“@variableName”, cID);

                return int.Parse(myCommand.ExecuteScalar().ToString());
            }
            catch (Exception ex)
            {
                DB.AddToExceptionLog(ex);
            }
            finally
            {
                conn.Close();
            }