I like things like this:
public static IEnumerable<IDataRecord> SqlRetrieve(string ConnectionString, string StoredProcName, Action<SqlCommand> addParameters)
{
using (SqlConnection cn = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand(StoredProcName, cn))
{
cn.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
if (addParameters != null)
{
addParameters(cmd);
}
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
yield return rdr;
}
}
}
What you get here is a reusable counter (you can change it to return a table), which the delegate accepts to provide parameters.
In real use, it looks something like this:
foreach (var dr in
SqlRetrieve(cn, sp,
delegate (SqlCommand cmd) {
cmd.Parameters.Add("@paramname", System.Data.SqlDbType.Int).Value = someint;
}
)
) {
}
Thus, you do not repeat all the same code, but only parts of the parameters. In your case, if you always return DataTables instead of getting a lot of code in a DataReader loop, the code can become even simpler.
source
share