Technical Article

Pagination in stored procedure

,

You recently published a script showing how to do pagination (e.g. results 20 - 30 of 100)

It's also possible to do it quicker and more elegantly without having to resort to building the sql string dynamically (never a good thing IMHO).

You pass in 2 parameters, @PageIndex is the first record you want (so number 1 the first time, 11 the second time, 21 etc if you're looking for 10 records), and @PageSize - the number of results you want returning.

As in the example you showed, this is using the 'Orders' table in Northwind database.

(I've used SQL pagination as an interview question for developers for a number of years, another answer was to get the first @pageindex + @pagesize, then sort it in descending order, then take the top @pagesize, it's slightly less efficient than this)

PROCEDURE [dbo].[uspOrderReport] (@PageIndex INT, @PageSize INT) AS

DECLARE @Rows INT
DECLARE @tempIDs TABLE
(
 [identity] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
 [OrderID] [int] NULL
)  --TO STORE THE SCORED TABLE

SELECT @Rows = (@PageIndex - 1 + @PageSize )
SET ROWCOUNT @Rows

INSERT INTO 
@tempIDs (OrderID)
SELECT 
OrderId 
FROM 
orders
ORDER BY OrderID

SELECT 
ORD.OrderId, 
ORD.CustomerId, 
ORD.EmployeeId 
FROM
orders ORD LEFT OUTER JOIN @tempIDs TID 
ON ORD.OrderID = TID.OrderID
WHERE 
TID.[identity] >= @PageIndex
ORDER BY ORD.OrderID

RETURN

Rate

4 (2)

You rated this post out of 5. Change rating

Share

Share

Rate

4 (2)

You rated this post out of 5. Change rating