日期:2014-05-17 浏览次数:20443 次
ALTER Procedure [dbo].[Common_DataPaging]
@tablestr varchar(8000), --查询语句
@FieldOrder varchar(200) , --排序字段(必须!支持多字段)
@StrWhere varchar(1000) = Null, --条件语句(不用加where)
@PageSize int = 15, --每页多少条记录
@CurrentPageIndex int = 1, --指定当前为第几页
@ReturnValue int output
AS
begin
Declare @sql nvarchar(max);Declare @totalRecord int;
declare @LastPageCount int;
if (@StrWhere='' or @StrWhere is NULL)
begin select @StrWhere=' ' end
else
begin select @StrWhere=' Where '+@StrWhere end
select @sql = N'select @totalRecord = count(1) from ( '+@tablestr+' ) as t '+@StrWhere
exec sp_executesql @sql, N'@totalRecord int out,@tablestr varchar(8000),@StrWhere varchar(1000)', @totalRecord out,@tablestr ,@StrWhere
--计算总页数
select @LastPageCount=CEILING((@totalRecord+0.0)/@PageSize);
select @ReturnValue=@LastPageCount;
select @sql = 'Select * FROM (select t.*,ROW_NUMBER() Over(order by ' + @FieldOrder + ') as rowId from (' + @tablestr+') as t ' + @StrWhere
--处理页数超出范围情况
if @CurrentPageIndex<=0 begin select @CurrentPageIndex = 1 end
if @CurrentPageIndex>@LastPageCount begin select @CurrentPageIndex = @LastPageCount end
--处理开始点和结束点
Declare @StartRecord int; Declare @EndRecord int;
select @StartRecord = (@CurrentPageIndex-1)*@PageSize + 1
select @EndRecord = @StartRecord + @PageSize - 1
select @Sql = @Sql + ') as tbname where rowId between ' + cast(@StartRecord as varchar(10)) + ' and ' + cast(@EndRecord as varchar(10))
Exec(@Sql)
End