Skip to main content
fixed to be more historically accurate
Source Link
Adam V
  • 6.4k
  • 3
  • 42
  • 52

When we used to work in MSSQL 2000, we did what we called the "triple-flip":

EDITED

DECLARE @InnerPageSize int DECLARE @OuterPageSize int DECLARE @Count int SELECT @Count = COUNT(<column>) FROM <TABLE> SET @InnerPageSize = @PageNum * @PageSize SET @OuterPageSize = @Count - ((@PageNum - 1) * @PageSize) IF (@OuterPageSize < 0) SET @OuterPageSize = 0 ELSE IF (@OuterPageSize > @PageSize) SET @OuterPageSize = @PageSize DECLARE @sql NVARCHAR(8000) SET @sql = 'SELECT * FROM ( SELECT TOP ' + CAST(pagesize@OuterPageSize AS nvarchar(5)) + ' * FROM ( SELECT TOP ' + CAST(n@InnerPageSize *AS pagesizenvarchar(5)) + ' * FROM X<TABLE> ORDER BY (column)<column> ASC ) AS t1 ORDER BY (column)<column> DESC ) AS t2 ORDER BY (column)<column> ASCASC' PRINT @sql EXECUTE sp_executesql @sql 

It wasn't elegant, and it wasn't fast, but it worked.

When we used to work in MSSQL 2000, we did what we called the "triple-flip":

SELECT * FROM ( SELECT TOP (pagesize) FROM ( SELECT TOP (n * pagesize) FROM X ORDER BY (column) ASC ) AS t1 ORDER BY (column) DESC ) AS t2 ORDER BY (column) ASC 

It wasn't elegant, and it wasn't fast, but it worked.

When we used to work in MSSQL 2000, we did what we called the "triple-flip":

EDITED

DECLARE @InnerPageSize int DECLARE @OuterPageSize int DECLARE @Count int SELECT @Count = COUNT(<column>) FROM <TABLE> SET @InnerPageSize = @PageNum * @PageSize SET @OuterPageSize = @Count - ((@PageNum - 1) * @PageSize) IF (@OuterPageSize < 0) SET @OuterPageSize = 0 ELSE IF (@OuterPageSize > @PageSize) SET @OuterPageSize = @PageSize DECLARE @sql NVARCHAR(8000) SET @sql = 'SELECT * FROM ( SELECT TOP ' + CAST(@OuterPageSize AS nvarchar(5)) + ' * FROM ( SELECT TOP ' + CAST(@InnerPageSize AS nvarchar(5)) + ' * FROM <TABLE> ORDER BY <column> ASC ) AS t1 ORDER BY <column> DESC ) AS t2 ORDER BY <column> ASC' PRINT @sql EXECUTE sp_executesql @sql 

It wasn't elegant, and it wasn't fast, but it worked.

Source Link
Adam V
  • 6.4k
  • 3
  • 42
  • 52

When we used to work in MSSQL 2000, we did what we called the "triple-flip":

SELECT * FROM ( SELECT TOP (pagesize) FROM ( SELECT TOP (n * pagesize) FROM X ORDER BY (column) ASC ) AS t1 ORDER BY (column) DESC ) AS t2 ORDER BY (column) ASC 

It wasn't elegant, and it wasn't fast, but it worked.