I have to call a stored procedure and get the results. I know there are various ways of doing this (as with all programming), and that I should be cleaning up the resources by calling Dispose()
and/or Close()
. Reading this close or dispose question I'm thinking that I should be using the using
statement and that should be enough. Below is how I'm making my call. My question is - am I over complicating this and will this clean up all of the resources?
private Int32 CallStoredProcedure(Int32 Id)
{
using (var dt = new DataTable())
{
using (var conn = new SqlConnection(ConnectionString))
{
using (var sqlCmd = new SqlCommand("SEL_StoredProcedure", conn))
{
using (var sda = new SqlDataAdapter(sqlCmd))
{
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@ID", Id);
sqlCmd.Connection.Open();
sda.Fill(dt);
}
}
}
if (dt.Rows.Count == 1)
return Convert.ToInt32(dt.Rows[0]["IDv2"]);
else if (dt.Rows.Count > 1)
throw new Exception("Multiple records were found with supplied ID; ID = " + studentId.ToString());
}
return 0;
}
P.S. - I know I could call ExecuteScalar
, but that's not what I'm looking for here since I will be using the general format for non-scalar calls.