SoFunction
Updated on 2025-04-08

About creating paging using stored procedures


Create PROCEDURE pagination3
@tblName varchar(255), --Table name
@strGetFields varchar(1000)= '*', -- Columns that need to be returned
@fldName varchar(255)='', --Sorted field name
@PageSize int = 10, -- Page size
@PageIndex int = 1, -- Page number
@doCount bit = 0, -- Return the total number of records, and return the value of non-0
@OrderType bit = 0, -- Set the sort type, non-0 values ​​will be descending
@strWhere varchar(1500) = '' -- Query conditions (Note: Don't add where)
AS

declare @strSQL varchar(5000) -- Subject statement
declare @strTmp varchar(110) -- Temporary variable
declare @strOrder varchar(400) --Sorting Type

if @doCount != 0
begin
if @strWhere !=''
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where '+@strWhere
else
set @strSQL = 'select count(*) as Total from [' + @tblName + '] '
end 
--The above code means that if the @doCount passes over is not 0, the total count will be executed. All the following codes are case where @doCount is 0:

else
begin
if @OrderType != 0
begin
set @strTmp = '<(select min'
set @strOrder = ' order by [' + @fldName +'] desc'
--If @OrderType is not 0, then perform descending order. This sentence is very important!

end
else
begin
set @strTmp = '>(select max'
set @strOrder = ' order by [' + @fldName +'] asc'
end

if @PageIndex = 1
begin
if @strWhere != '' 

set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from [' + @tblName + '] where ' + @strWhere + ' ' + @strOrder
else

set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from ['+ @tblName + '] '+ @strOrder
--If it is the first page, execute the above code, which will speed up the execution speed
end
else
begin
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from ['
+ @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @fldName + ']  from [' + @tblName + ']' + @strOrder + ') as tblTmp)'
+ @strOrder

if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from ['
+ @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @fldName + '] from [' + @tblName + '] where ' + @strWhere + ' '
+ @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
end
end
exec (@strSQL)
--print @strSQL
GO