I slightly changed the generics circulating on the Internet, and even the results of the table query can be returned.
create PROC [dbo].[PageView] ( @sql nvarchar(max),---Original query statement @PageIndex int, --page number @PageSize int, -- the number of records per page @Sort VARCHAR(255), --sort fields and rules, no need to add order by @GetCount bit -- whether to get the total number of records 1 is to get the total number of records, 0 is to not get the total number of records, return the record set ) AS declare @strSql nvarchar(max) set nocount on; if(@GetCount = 1) begin set @strSql=' SELECT COUNT(*) as getrowcount FROM ('+@sql+') t' end else begin set @strSql=' SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY ' + @Sort + ') AS rownum, * FROM ('+@sql+') AS Dwhere ) t WHERE t.rownum BETWEEN ' + CAST(((@PageIndex-1)*@PageSize + 1) as varchar(20)) + ' and ' + cast((@PageIndex*@PageSize) as varchar(20)) end exec (@strSql) set nocount off;
do it
exec book.dbo.PageView 'select * from book where id<58385557',1,2,'id desc',1 exec book.dbo.PageView 'select * from book where id<58385557',1,2,'id desc',0
result