SoFunction
Updated on 2025-04-08

Pagination of SQL Server stored procedures

Create a table:

CREATE TABLE [TestTable] ( 
[ID] [int] IDENTITY (1, 1) NOT NULL , 
[FirstName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL , 
[LastName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL , 
[Country] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL , 
[Note] [nvarchar] (2000) COLLATE Chinese_PRC_CI_AS NULL 
) ON [PRIMARY] 
GO 

Insert data: (20,000 pieces, it will be more obvious if you test it with more data)
SET IDENTITY_INSERT TestTable ON 

declare @i int 
set @i=1 
while @i<=20000 
begin 
insert into TestTable([id], FirstName, LastName, Country,Note) values(@i, ''FirstName_XXX'',''LastName_XXX'',''Country_XXX'',''Note_XXX'') 
set @i=@i+1 
end 

SET IDENTITY_INSERT TestTable OFF 

------------------------------------- 

Pagination plan 1: (Use Not In and SELECT TOP paging)
Statement form:
SELECT TOP 10 * 
FROM TestTable 
WHERE (ID NOT IN 
(SELECT TOP 20 id 
FROM TestTable 
ORDER BY id)) 
ORDER BY ID 

SELECT TOP Page Size*
FROM TestTable 
WHERE (ID NOT IN 
(SELECT TOP Page size * Number of pages id
FROM table
ORDER BY id)) 
ORDER BY ID 

------------------------------------- 

Pagination scheme 2: (Use the ID greater than what and SELECT TOP pagination)
Statement form:
SELECT TOP 10 * 
FROM TestTable 
WHERE (ID > 
(SELECT MAX(id) 
FROM (SELECT TOP 20 id 
FROM TestTable 
ORDER BY id) AS T)) 
ORDER BY ID 

SELECT TOP Page Size*
FROM TestTable 
WHERE (ID > 
(SELECT MAX(id) 
FROM (SELECT TOP Page size*Page number id
FROM table
ORDER BY id) AS T)) 
ORDER BY ID 

------------------------------------- 

Pagination scheme 3: (Pagination using SQL cursor stored procedure)
create procedure XiaoZhengGe 
@sqlstr nvarchar(4000), --Query string
@currentpage int, --Page N
@pagesize int --Number of rows per page
as 
set nocount on 
declare @P1 int, --P1 is the id of the cursor
@rowcount int 
exec sp_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount output 
select ceiling(1.0*@rowcount/@pagesize) as Total number of pages--,@rowcount as Total number of rows, @currentpage as Current page
set @currentpage=(@currentpage-1)*@pagesize+1 
exec sp_cursorfetch @P1,16,@currentpage,@pagesize 
exec sp_cursorclose @P1 
set nocount off 

Other solutions: If there is no primary key, you can use temporary tables or Scheme 3, but the efficiency will be low.
It is recommended that when optimizing, add primary keys and indexes, the query efficiency will be improved.

Through the SQL query analyzer, the comparison is displayed: My conclusion is:
Pagination scheme 2: (using the ID greater than what and SELECT TOP paging) is the most efficient, and SQL statements need to be spliced
Pagination scheme 1: (Using Not In and SELECT TOP paging) The efficiency is second, and SQL statements need to be spliced.
Paging Solution 3: (Pagination using SQL cursor stored procedures) The worst efficiency, but the most general

In actual situations, specific analysis is required.