我想对存储过程结果中的列进行排序,而不必在存储过程中添加 Order By 子句。我不希望在执行查询后对数据进行排序,如果可能的话,排序应该是查询的一部分。我有以下代码:
public static DataTable RunReport(ReportQuery query)
{
OffertaDataContext db = new OffertaDataContext();
Report report = (from r in db.Reports where r.Id == (int)query.ReportId select r).Single();
//???: check security clearance.
DataSet dataSet = new DataSet();
/*
doesn't work, I guess the "Result" table hasn't been created yet;
if(!string.IsNullOrEmpty(query.SortField))
{
dataSet.DefaultViewManager.DataViewSettings["Result"].Sort = query.SortField + " " + (query.SortAscending ? "ASC" : "DESC");
}
*/
using (SqlConnection conn = new SqlConnection(Config.ConnectionString))
{
conn.Open();
using (SqlCommand exec = conn.CreateCommand())
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
exec.Connection = conn;
exec.CommandType = CommandType.StoredProcedure;
exec.CommandText = report.ReportProc;
adapter.SelectCommand = exec;
try
{
adapter.Fill(dataSet, query.Skip, query.Take, "Result");
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
}
return dataSet.Tables["Result"];
}
}
}
}
如何添加排序?
最佳答案
获取您在数据集中填充的数据表(“结果”)。
现在 - 没有办法对 DataTable 进行排序,除非通过查询、 View 或存储 填充它的过程。
因为你不想在 SP 中这样做,你可以排序 DefaultView 的 DataTable,或与 DataTable 关联的任何 DataView。
您可以使用 DataView 的 Sort 属性来实现它。这是一个字符串,它指定要排序的列(或列)以及顺序(ASC 或 DESC)。
例子:
myTable.DefaultView.Sort = "myColumn DESC";
你现在可以使用 DefaultView 做任何你想做的事情(将它绑定(bind)到某物或任何东西上)
关于c# - 对存储过程的结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/323342/