ADO.NET Reading from Database w stored procedures
//Reading single value if the SP returns single value..Output parameter is more efficient than this but sometimes required
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["QFlowDB"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("cqf.CustomerGetByNameAndBirthday", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FirstName", firstName);
cmd.Parameters.AddWithValue("@LastName", lastName);
cmd.Parameters.AddWithValue("@DOB", DateTime.ParseExact(dob, "MMddyyyy", CultureInfo.InvariantCulture).Date);
conn.Open();
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
//load into the result object the returned row from the database
if (dataReader.HasRows)
{
dataReader.read();
//assume cqf.CustomerGetByNameAndBirthday gives single value
return (int)dataReader["CustomerId"];
}
}
}
}
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["QFlowDB"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("cqf.CustomerGetByNameAndBirthday", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FirstName", firstName);
cmd.Parameters.AddWithValue("@LastName", lastName);
cmd.Parameters.AddWithValue("@DOB", DateTime.ParseExact(dob, "MMddyyyy", CultureInfo.InvariantCulture).Date);
SqlParameter customerIdParam = new SqlParameter("customerIdParamInStoredProcedure", SqlDbType.Int);
customerIdParam.Direction = ParameterDirection.Output;
command.Parameters.Add(customerIdParam);
conn.Open();
command.ExecuteNonQuery();
//If customerIdparam doesn't get value from stored procedure, it will be null. So checking against DBNULL
if(customerIdParam.value != DBNull.Value){
customerId = (int)customerIdParam.Value;
}
}
}