sqlserver分页存储过程

稍微把网上流传的通用改了一下,连表查询的结果也能返回了

create PROC [dbo].[PageView]

(
@sql nvarchar(max),---原本查询语句
@PageIndex int, --页码
@PageSize int, --每页容纳的记录数
@Sort VARCHAR(255), --排序字段及规则,不用加order by
@GetCount bit --是否得到记录总数 1为得到记录总数,0为不得到记录总数,返回记录集
)
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;

  

执行一下

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

  

结果

猜你喜欢

转载自www.cnblogs.com/SakugamiTomoyo/p/8875854.html