首页 > 代码库 > SQL 存储过程 分页

SQL 存储过程 分页

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go




-- =============================================
-- Author: ***
-- Create date: 2014-03-27 20:00
-- Description: 采用最新的 row_number() over 技术高效分页方法
-- =============================================
ALTER PROCEDURE [dbo].[P_Public_Paging]
@TableName Nvarchar(4000), --要显示的表、视图、或是SQL语句
@FieldName nvarchar(4000) = ‘*‘, --要显示的字段列表,所有字段是* 大视图最好不要用*
@PageSize int, --每页显示的记录个数(每页条数小于1则修正成10)
@PageIndex int=1, --要显示那一页的记录(当前页小于1或自动修正为1)
@Where  nvarchar(2000) = ‘1=1‘, --查询条件,不需where
@OrderBy nvarchar(2000), --排序字段,最好是索引字段
@PageCount int = 1 output, --返回分页后的总页数
@RecordCount int =0 output --返回查询到的记录数
AS
BEGIN
Declare @SelectSql nvarchar(4000) --构造Sql查询词句
if @PageSize < 1 set @PageSize = 10--如果小每页大小小于1则修正成10
set @SelectSql = ‘ select @RecordCount = count(0) from ‘ + @TableName + ‘ where ‘ + @Where
exec sp_executesql @SelectSql ,N‘@RecordCount int out ‘,@RecordCount out
--计算@PageCount的值
if @RecordCount <= @PageSize
set @PageCount = 1
else if @RecordCount % @PageSize = 0
set @PageCount = (@RecordCount / @PageSize )
else
set @PageCount = (@RecordCount / @PageSize ) + 1
--检查@PageIndex的值
if @PageIndex> @PageCount
set @PageIndex= @PageCount
if @PageIndex < 1
set @PageIndex = 1
set @SelectSql = ‘select ‘+@FieldName +‘from (‘ +
‘select row_number() over (order by ‘ + @OrderBy + ‘)  RowID ,‘ + @FieldName +
‘ from ‘ + @TableName + ‘ where ‘ + @Where +
‘) a where a.RowID > ‘ + cast((@PageIndex -1) * @pageSize as varchar(128)) +
‘ and a.RowID <= ‘ + cast(@PageIndex * @pageSize as varchar(128))
exec sp_executesql @SelectSql
select @PageCount,@RecordCount
END