在显示数据时提供第 n 页的最佳 t-sql?

best t-sql for providing nth page in showing data?

我想使用

在第一页中显示第 1 到 50 项
SELECT TOP(50) * 
FROM Items_table 

它工作正常,但我怎样才能获得下一页的第二个 50 项?查询应该如何?

请注意,我无法使用 LIMIT,因为我正在使用 SQL 服务器。

我对以下查询也有疑问:

select * 
from (
    select 
        ROW_NUMBER() over (
            ORDER BY date_of_creation desc, time_of_creation desc) AS Row2,
        * 
    from 
        Items_table) ir
where 
    ir.Row2 between @start and @end

问题出在这种情况下 table 适配器不支持 OVER

table 适配器是否支持任何其他 t-sql 代码?

如果您使用的是 SQL Server 2012 或更高版本,那么这会对您有所帮助

DECLARE @RowsPerPage INT = 50; 
DECLARE @PageNumber INT = 2; 

SELECT *
FROM ItemsTable
ORDER BY date_of_creation desc, time_of_creation desc
OFFSET (@PageNumber - 1) * @RowsPerPage ROWS
FETCH NEXT @RowsPerPage ROWS ONLY

变量@PageNumber 指定您要检索的页面(第一个、第二个..等)

我在 table 适配器中通过此查询实现了这一点:

select top (@count) * 
from Items_table
where id not in (select top(@count2) id from Items_table)
order by Date_Of_Creation desc,Time_Of_Creation desc

感谢参与。

更新:请不要在内部查询中使用排序权,因为我有重复的结果和一些错误。另外当你要加载第10页时,查询的性能会很差(执行查询所需的时间不是acceptable)。

我被迫使用这个方法(而且也很好):

Select TOP (@count) from Item_table
order by Date_Of_Creation desc,Time_Of_Creation desc

然后每个页面应该包含这个查询的一些行(如果你打算使用多页)。

如果您有一个页面,当用户到达底部时您想要加载更多,在这种方法中,您应该在每次您想要使用更大的@count 加载更多并加载页面中的项目时执行此查询。

如果你想在 sql 2008 年编写代码,试试这个:

    Drop Table T1 ;
GO
Create Table T1( id int, Title varchar(100) );
Insert T1 Values
( 1000, 'A1000' ),( 1001, 'A1001' ),( 1002, 'A1002' ),( 1003, 'A1003' ),( 1004, 'A1004' ),
( 1005, 'A1005' ),( 1006, 'A1006' ),( 1007, 'A1007' ),( 1008, 'A1008' ),( 1009, 'A1009' ),
( 1010, 'A1010' ),( 1011, 'A1011' ),( 1012, 'A1012' ),( 1013, 'A1013' ),( 1014, 'A1014' ),
( 1015, 'A1015' ),( 1016, 'A1016' ),( 1017, 'A1017' ),( 1018, 'A1018' ),( 1019, 'A1019' );
GO


Declare @PageNO int =1, @RowsPerPage int =5;
Select Rw,Id, Title FROM
(
    Select 
        Rw=Row_number() Over( order by Id ) , Id, Title 
    from T1
) A
where Rw between (@PageNO-1)*@RowsPerPage+1 and @PageNO*@RowsPerPage