sqlserver分页存储过程

时间:2018-04-18 16:50:08   收藏:0   阅读:190

 

 

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

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

  

结果

技术分享图片

原文:https://www.cnblogs.com/SakugamiTomoyo/p/8875854.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!