使用sql2005的新特性分页的储存过程:Top,Row_Number
GO
/****** 对象: StoredProcedure [dbo].[uspCustomPaging] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [dbo].[uspCustomPaging]
@TableName varchar(50), --表或视图名
@Fields varchar(5000) = '*', --字段名(全部字段为*)
@OrderFields varchar(5000), --排序字段(必须!支持多字段,建议建索引)
@SqlWhere varchar(5000) = '', --条件语句(如and Name='a')
@PageSize int, --每页多少条记录
@PageIndex int = 1 , --指定当前为第几页
@TotalPages int output --返回总页数
as
begin
declare @sql nvarchar(4000)
declare @TotalRecords int
--计算总记录数及总页数
set @sql = 'select @TotalRecords = count(*) from ' + @TableName + ' where 1=1 ' + @sqlWhere
exec sp_executesql @sql,N'@totalRecords int output',@TotalRecords output
select @TotalPages=CEILING((@TotalRecords+0.0)/@PageSize)
--处理页数超出范围情况
if @PageIndex<=0
set @PageIndex = 1
if @PageIndex>@TotalPages
set @PageIndex = @TotalPages
set @sql = 'select '+ @Fields + ' from (select top(@PageIndex*@PageSize) ' + @Fields + ',row_number() over(order by ' + @OrderFields + ') as rowNumber from ' + @TableName + ' where 1=1 ' + @SqlWhere + ') t where t.rowNumber >= ((@PageIndex-1)*@PageSize+1)'
--print @Sql
exec sp_executesql @sql,N'@PageIndex int, @PageSize int',@PageIndex,@PageSize
end
/****** 对象: StoredProcedure [dbo].[uspCustomPaging] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [dbo].[uspCustomPaging]
@TableName varchar(50), --表或视图名
@Fields varchar(5000) = '*', --字段名(全部字段为*)
@OrderFields varchar(5000), --排序字段(必须!支持多字段,建议建索引)
@SqlWhere varchar(5000) = '', --条件语句(如and Name='a')
@PageSize int, --每页多少条记录
@PageIndex int = 1 , --指定当前为第几页
@TotalPages int output --返回总页数
as
begin
declare @sql nvarchar(4000)
declare @TotalRecords int
--计算总记录数及总页数
set @sql = 'select @TotalRecords = count(*) from ' + @TableName + ' where 1=1 ' + @sqlWhere
exec sp_executesql @sql,N'@totalRecords int output',@TotalRecords output
select @TotalPages=CEILING((@TotalRecords+0.0)/@PageSize)
--处理页数超出范围情况
if @PageIndex<=0
set @PageIndex = 1
if @PageIndex>@TotalPages
set @PageIndex = @TotalPages
set @sql = 'select '+ @Fields + ' from (select top(@PageIndex*@PageSize) ' + @Fields + ',row_number() over(order by ' + @OrderFields + ') as rowNumber from ' + @TableName + ' where 1=1 ' + @SqlWhere + ') t where t.rowNumber >= ((@PageIndex-1)*@PageSize+1)'
--print @Sql
exec sp_executesql @sql,N'@PageIndex int, @PageSize int',@PageIndex,@PageSize
end