Thursday, March 28, 2013

Achieve SQL Server Pagination Using OFFSET and FETCH Feature in SQL Server 2012


In the below example you would see that I have created a stored procedure namely PersonNameAndLocationUsingSQLServerPagingFeature which will help me achieve SQL Server Pagination by leveraging OFFSET and FETCH feature in SQL Server 2012.
Use AdventureWorks2008R2
GO
 
IF EXISTS (SELECT * FROM sys.objects WHERE object_id =
    OBJECT_ID
(N'[dbo].[PersonNameAndLocationUsingSQLServerPagingFeature]') AND type in (N'P', N'PC'))
DROP
PROCEDURE [dbo].[PersonNameAndLocationUsingSQLServerPagingFeature]
GO
 
CREATE PROCEDURE PersonNameAndLocationUsingSQLServerPagingFeature
(

           
@StartingRowNumber    INT,
           
@RowCountPerPage      INT
 
)

AS
BEGIN

    SELECT

           
 PP.FirstName + ' ' + PP.LastName AS 'Name'
           
,PA.City
           
,PA.PostalCode

    FROM
  Person.Address PA
           
INNER JOIN
                       
Person.BusinessEntityAddress PBEA
                                   
ON PA.AddressID = PBEA.AddressID
           
INNER JOIN
                       
Person.Person PP
                                   
ON PBEA.BusinessEntityID = PP.BusinessEntityID

    ORDER
BY PP.FirstName
             
OFFSET (@StartingRowNumber - 1) * @RowCountPerPage ROWS
           
              FETCH NEXT @RowCountPerPage ROWS ONLY

END
GO

No comments: