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
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
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
(
@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