SQL分页排序

SQL分页排序,sql,sorting,paging,Sql,Sorting,Paging,我需要在网页上显示网格。数据将通过存储过程来自SQL Server 2008。由于存储过程返回数千条记录,我决定选择一个工作正常的分页选项。在存储过程中,我执行以下操作: declare @RowIdMin int=10 declare @RowIdMax int=25 select * from (select Col1, Col2, ROW_NUMBER() over (order by Col1 desc) as RowId from MyTable ) dt

我需要在网页上显示网格。数据将通过存储过程来自SQL Server 2008。由于存储过程返回数千条记录,我决定选择一个工作正常的分页选项。在存储过程中,我执行以下操作:

declare @RowIdMin int=10  
declare @RowIdMax int=25  

select * 
from (select Col1, Col2, ROW_NUMBER() over (order by Col1 desc) as RowId  
      from MyTable ) dt  
where RowId BETWEEN @RowIdMin AND @RowIdMax    
只要用户愿意获得按Col1排序的数据,这种方法就可以正常工作。如果我事先不知道记录集必须按哪个列排序,我怎么能重写它呢?这不起作用:

declare @RowIdMin int=10  
declare @RowIdMax int=25  
声明@ColSort varchar100='MyColumn'


当@ColSort='ABC'然后是ABC时,从MyTable按大小写排序

更透彻的解释


动态SQL可能是您最好的选择;交换行号函数中的排序选项。您也可以参数化executesql中的选项,请参见


我完全同意其他文章,动态SQL或CASE语句order by是实现这一点的选项,正如您所描述的


但是,作为旁白,请看一下您正在使用的框架的其余部分。如果它的asp.NET3.5,那么它的内置网格和linq将用很少的努力为您完成所有这些。试试看。

我将为200 Alex进行SQL注入!任何不验证输入的人都应该使用它们来生成输出,这就是为什么对他的回答有评论的原因。
select * 
from (select Col1, Col2, ROW_NUMBER() over (order by <b>@ColSort</b> desc) as RowId  
from MyTable) dt  
where RowId BETWEEN @RowIdMin AND @RowIdMax   
declare @SQLScript nVarchar(4000)

declare @RowIdMin int=10
declare @RowIdMax int=25
declare @ColSort varchar(100)='MyColumn'


Select @SQLScript = 'select * from (select Col1, Col2, ROW_NUMBER() over (order by ' + @ColSort + 'desc) as RowId from MyTable  dt where RowId BETWEEN ' + cast(@RowIdMin as nvarchar(100))+ ' AND ' + cast(@RowIdMax as nvarchar(100))

exec sp_executesql @SQLScript