简体   繁体   English

对存储过程的结果进行排序

[英]Sorting the result of a stored procedure

I'd like to sort on a column in the result of a stored procedure without having to add the Order By clause in the stored procedure. 我想在存储过程的结果中对列进行排序,而不必在存储过程中添加Order By子句。 I don't want the data to be sorted after I have executed the query, sorting should be part of the query if possible. 我不希望在执行查询后对数据进行排序,如果可能,排序应该是查询的一部分。 I have the following code: 我有以下代码:

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"];
            }
        }
    }
}

How do I add sorting? 如何添加排序?

Get the DataTable you are populating in the dataSet ("Result"). 获取您在dataSet中填充的DataTable(“Result”)。

Now - there's no way to sort the DataTable, except via the Query, View, or Stored Procedure that populates it. 现在 - 除了通过填充它的查询,视图或存储过程之外,没有办法对DataTable进行排序。

Since you don't wanna do it in the SP, you can sort the DefaultView of the DataTable, or any DataView that is associated with the DataTable. 由于您不想在SP中执行此操作,因此可以对DataTable的DefaultView或与DataTable关联的任何DataView进行排序。

You can achieve it using the Sort property of the DataView. 您可以使用DataView的Sort属性来实现它。 This is a string which specifies the column (or columns) to sort on, and the order (ASC or DESC). 这是一个字符串,它指定要排序的列(或列)和顺序(ASC或DESC)。

Example: 例:

myTable.DefaultView.Sort = "myColumn DESC";

You can now use the DefaultView to do whatever you want (bind it to something or whatever) 您现在可以使用DefaultView执行任何操作(将其绑定到某些内容或其他内容)

To be honest, since you are using DataTable, you might as well just sort at the client. 说实话,既然您正在使用DataTable,那么您也可以在客户端进行排序。

Dynamic sorting (at the server) via SPs etc is always a pain; 通过SP等动态排序(在服务器上)总是很痛苦; to do it in pure TSQL, you either need some horribly inefficient CASE block at the end of the SELECT, or you need to use dynamic SQL (for example via sp_ExecuteSQL), manipulating the ORDER BY in the final query. 要在纯TSQL中执行它,您需要在SELECT结束时使用一些非常低效的CASE块,或者您需要使用动态SQL(例如通过sp_ExecuteSQL),在最终查询中操作ORDER BY。 The only other option (in raw TSQL) would be to EXEC/INTO to get the data into a table variable (or temp table), then SELECT from this with an ORDER BY. 唯一的另一个选择(在原始TSQL中)是EXEC / INTO将数据放入表变量(或临时表),然后使用ORDER BY从中获取SELECT。

If it is an option, LINQ-to-SQL actually does OK at this; 如果它是一个选项,LINQ-to-SQL实际上就可以了; it supports querying (and composing against) UDFs - so rather than an SP, code the query in a UDF (the SP can always just SELECT from the UDF if you need to support legacy callers). 它支持查询(和编写)UDF - 因此,而不是SP,在UDF中编码查询(如果您需要支持传统调用者,SP始终只能从UDF中进行SELECT)。 Then you can use "order by" etc in a LINQ query: 然后你可以在LINQ查询中使用“order by”等:

var qry = from row in ctx.SomeMethod(args)
          order by row.Name, row.Key
          select row;

(or there are various methods for adding a dynamic sort to a LINQ query - the above is just a simple example) (或者有各种方法为LINQ查询添加动态排序 - 上面只是一个简单的例子)

the final TSQL will be something like: 最终的TSQL将是这样的:

SELECT blah FROM theudf(args) ORDER BY blah

ie it will get it right, and do the "ORDER BY" at the server. 即它会正确,并在服务器上执行“ORDER BY”。 This is particularly useful when used with Skip() and Take() to get paged data. 当与Skip()Take()以获取分页数据时,这尤其有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM