Quantcast
Channel: How to select the nth row in a SQL database table? - Stack Overflow
Viewing all articles
Browse latest Browse all 35

Answer by Adam V for How to select the nth row in a SQL database table?

$
0
0

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

EDITED

DECLARE @InnerPageSize intDECLARE @OuterPageSize intDECLARE @Count intSELECT @Count = COUNT(<column>) FROM <TABLE>SET @InnerPageSize = @PageNum * @PageSizeSET @OuterPageSize = @Count - ((@PageNum - 1) * @PageSize)IF (@OuterPageSize < 0)    SET @OuterPageSize = 0ELSE IF (@OuterPageSize > @PageSize)    SET @OuterPageSize = @PageSizeDECLARE @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 @sqlEXECUTE sp_executesql @sql

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


Viewing all articles
Browse latest Browse all 35

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>