Monday, August 10, 2015

Paging with SQL

In MySQL, this can be easily done with:

SELECT * FROM tbl limit [start], [end]

In MSSQL, this can be done as in [1] :

1.Paging rows with Limit (MSSQL 2005 or later)

--VIEWING THE PAGE "2" WITH 5 ROWS
DECLARE @PageNumber AS INT, @RowspPage AS INT
SET @PageNumber = 2
SET @RowspPage = 5 SELECT * FROM (
             SELECT ROW_NUMBER() OVER(ORDER BY ID_EXAMPLE) AS NUMBER,
                    ID_EXAMPLE, NM_EXAMPLE, DT_CREATE FROM TB_EXAMPLE
               ) AS TBL
WHERE NUMBER BETWEEN ((@PageNumber - 1) * @RowspPage + 1) AND (@PageNumber * @RowspPage)
ORDER BY ID_EXAMPLE


2. Paging in SQL Server 2012, with FETCH/OFFSET

--CREATING A PAGING WITH OFFSET and FETCH clauses IN "SQL SERVER 2012"
DECLARE @PageNumber AS INT, @RowspPage AS INT
SET @PageNumber = 2
SET @RowspPage = 10 

SELECT ID_EXAMPLE, NM_EXAMPLE, DT_CREATE
FROM TB_EXAMPLE
ORDER BY ID_EXAMPLE
OFFSET ((@PageNumber - 1) * @RowspPage) ROWS
FETCH NEXT @RowspPage ROWS ONLY;


For performance, 2 is better than 1. Both are better than getting all rows and use specific range.

[1] http://social.technet.microsoft.com/wiki/contents/articles/23811.paging-a-query-with-sql-server.aspx


No comments:

Blog Archive

Followers