command.ExecuteReader have result code example
Example 1: C# mysql data reader from two tables
using (SqlConnection connection = new SqlConnection("connection string here"))
{
using (SqlCommand command = new SqlCommand
("SELECT Column1 FROM Table1; SELECT Column2 FROM Table2", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
MessageBox.Show(reader.GetString(0), "Table1.Column1");
}
if(reader.NextResult())
{
while (reader.Read())
{
MessageBox.Show(reader.GetString(0), "Table2.Column2");
}
}
}
}
}
Example 2: C# function return datareader
private IEnumerable<T> GetRows<T>(string sql, Action<SqlParameterCollection> addParameters, Func<IDataRecord, T> copyRow)
{
using (var cn = new SqlConnection("Connection string here"))
using (var cmd = new SqlCommand(sql, cn)
{
cmd.CommandType = CommandType.StoredProcedure;
addParameters(cmd.Parameters);
cn.Open();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
yield return copyRow(rdr);
}
rdr.Close();
}
}
}
public IEnumerable<MenuItem> GetChildMenus(string url)
{
return GetRows<MenuItem>("spR_GetChildMenus", p =>
{
p.AddWithValue("@PageUrl", url);
p.AddWithValue("@MenuId", ParameterDirection.Output);
p.AddWithValue("@ParentId", ParameterDirection.Output);
p.AddWithValue("@TitleText", ParameterDirection.Output);
p.AddWithValue("@ExternalUrl", ParameterDirection.Output);
p.AddWithValue("@FullUrl", ParameterDirection.Output);
p.AddWithValue("@ChildCount", ParameterDirection.Output);
}, r =>
{
return new MenuItem( ... );
}
}