I'm refactoring a C# program that calls a stored procedure that ends with:
SELECT @ResultCode AS ResultCode
The C# code looks like this:
SqlDbCommand.CommandType = System.Data.CommandType.StoredProcedure;
SqlDbCommand.CommandText = "PR_Foo";
SqlDbCommand.Parameters.Clear();
SqlDbCommand.Parameters.Add("@Foo", SqlDbType.Char);
SqlDbCommand.Parameters["@Foo"].Value = 'Foo';
System.Data.SqlClient.SqlDataAdapter SqlDbAdapter = new System.Data.SqlClient.SqlDataAdapter();
System.Data.DataSet SQLDataSet = new System.Data.DataSet();
SqlDbAdapter.SelectCommand = SqlDbCommand;
SqlDbAdapter.Fill(SQLDataSet);
SQLDataSet.Tables[0].TableName = "PR_Foo";
if (SQLDataSet.Tables.Count != 0) {
Result = int.Parse(SQLDataSet.Tables[SQLDataSet.Tables.Count - 1].Rows[0][0].ToString());
}
With the above code, Result
is correctly populated with the value returned by the
stored procedure.
Refactoring the code with a simpler ExecuteScalar
:
SqlDbCommand.CommandType = System.Data.CommandType.StoredProcedure;
SqlDbCommand.CommandText = "PR_Foo";
SqlDbCommand.Parameters.Clear();
SqlDbCommand.Parameters.Add("@Foo", SqlDbType.Char);
SqlDbCommand.Parameters["@Foo"].Value = 'Foo';
Result = (int)SqlDbCommand.ExecuteScalar();
the Result
value is oddly set to 0 while the expected result should be an integer value greater than zero.
Do you know what could be the cause of this strange behavior?
Note:
the stored procedure has several if blocks, returning result values lower than zero in case of particular checks; these cases are correctly handled by the ExecuteScalar().
The problem raises when the stored procedure does its job correctly, committing the transactions of the various updates and returning the Result
value at the end.