T-SQL:ORDER BY“表达式”
所有将数据返回到我当前正在开发的 Web 服务的表示层的存储过程都将两个整数作为参数:@StartingRow 和 @MaximumRows,这样我就可以对结果进行分页,而无需每次都检索整个结果列表。现在我想在这些程序中引入排序,但是据我所知,每个人都使用动态SQL来进行排序:
EXEC ( 'WITH [Results] AS
( SELECT * ,
ROW_NUMBER() OVER ( ORDER BY ' + @SortExpression + @Direction + ') AS 'RowNumber'
FROM [SomeTable] )
SELECT [Column1] , [Column2]
WHERE ( [RowNumber] BETWEEN ' + @StartingRow +
' AND ( ' + @StartingRow + ' + ' + @MaximumRows + ' - 1) )' )
这种方法的问题是,由于客户的需求,我不能使用动态SQL,所以我无法指定结果排序所依据的列。那我有什么选择呢?
All stored procedures which return data to the presentation layer of the webservice I am currently developing take as parameters two integers, @StartingRow
and @MaximumRows
, so that I can paginate results without retrieving the whole result list everytime. Now I would like to introduce sorting in these procedures, but from what I see everyone uses dynamic SQL to do the ordering:
EXEC ( 'WITH [Results] AS
( SELECT * ,
ROW_NUMBER() OVER ( ORDER BY ' + @SortExpression + @Direction + ') AS 'RowNumber'
FROM [SomeTable] )
SELECT [Column1] , [Column2]
WHERE ( [RowNumber] BETWEEN ' + @StartingRow +
' AND ( ' + @StartingRow + ' + ' + @MaximumRows + ' - 1) )' )
The problem with this approach is that I can't use dynamic SQL due to customer's demand, so that I can't specify the column according to which the results should be sorted. What are my options, then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
案例
。当@SortParameter
等于 1 时,此示例按Col1
排序。对于参数 5,它按Col2
降序排序。SQL Server 无法通过这种方法使用索引。这是使用动态 SQL 的主要原因。
You could use a
case
. This example sorts onCol1
when@SortParameter
equals 1. For parameter 5, it sorts byCol2
in descending order.SQL Server cannot use indexes with this approach. Which is the prime reason for using dynamic SQL instead.