SqlServer分页存储过程

原创
2018/09/07 11:57
阅读数 359

-----------------------------------------------------------------sqlserver分页----------------------------------------------------------------
/**********************************************************************
参数:@PrimaryKey 主键,@OrderBy 排序字段,@SqlStr sql语句,@PageSize 每页显示的记录,@PageIndex 当前页(从0开始)
***********************************************************************/
create procedure [dbo].[PageQuery]
@PrimaryKey varchar(100),--主键
@OrderBy varchar(100),--排序字段
@SqlStr varchar(8000),--sql语句
@PageSize int,--每页显示的记录
@PageIndex int--当前页(从0开始)
--@RecordCount int output --返回的总记录数
as
declare @ExecSql varchar(8000)--要执行的Sql组合
if @OrderBy=''
	set @OrderBy='order by '+@PrimaryKey+' asc'
else if (len(@OrderBy)<8 or upper(substring(@OrderBy,1,8))<>'ORDER BY')
	set @OrderBy='order by '+@OrderBy
--if((len(@OrderBy)>0) and(len(@OrderBy)<8 or upper(substring(@OrderBy,1,8))<>'ORDER BY'))
--	set @OrderBy='order by '+@OrderBy
if @PageSize=-1--用于ajax的第一次查询
	set @PageSize=0
bin
	declare @recordCount int,@pageCount int
	declare @s nvarchar(4000)
	set @s = N'select @recordCount = count('+@PrimaryKey+') from ('+@SqlStr+') TN'
	exec sp_executeSql @s,N'@recordCount int output',@recordCount output
	if(@pageSize>0)
		set @pageCount = (@recordCount - 1 + @PageSize) / @PageSize;--总页数
	else
		set @pageCount = 0;--总页数
	if(@pageCount<(@PageIndex+1))
	bin
		set @pageCount=@pageCount-1
		exec PageQuery @PrimaryKey,@OrderBy,@SqlStr,@PageSize,@pageCount
	end
	else
	bin
		if @PageIndex<=0--如果是第一页就执行这个
			bin
				set @ExecSql='select top '+cast(@PageSize as varchar(100))+' * from ('+@SqlStr+') T '+@OrderBy
			end
		else
			bin
				if charindex('2000 - 8.00.',@@version)>0
					bin
						set @ExecSql=
						'select top '+cast(@PageSize as varchar(100))+' *
						from ('+@SqlStr+') as T where T.'+@PrimaryKey+' not in
						(select top '+cast((@PageSize*@PageIndex) as varchar(100))+' '+@PrimaryKey+'
							from ('+@SqlStr+') T2 '+@OrderBy+') '+ @OrderBy
					end
				else
					bin
						set @ExecSql=
						'select * from
						(
							select * from
							(SELECT *, #RowNum#=ROW_NUMBER() OVER('+@OrderBy+') FROM ('+@SqlStr+') T1) T2 where T2.#RowNum#>='+cast(@PageSize*@PageIndex+1 as varchar(10))+' and T2.#RowNum#<='+cast(@PageSize*(@PageIndex+1) as varchar(10))+'
						) T3
						'
					end
			end
			exec (@ExecSql+' select '+@recordCount+' as RecordCount,'+@pageCount+' as PageCount ')
	end
end

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
在线直播报名
返回顶部
顶部