Alter Procedure [dbo].[up_Page2005]
@TableName varchar(50), --表名
@FIElds varchar(5000) = '*', --字段名(全部字段為*)
@OrderFIEld varchar(5000), --排序字段(必須!支持多字段)
@sqlWhere varchar(5000) = Null,--條件語句(不用加where)
@pageSize int, --每頁多少條記錄
@pageIndex int = 1 , --指定當前為第幾頁
@TotalPage int output --返回總頁數
as
begin
Begin Tran --開始事務
Declare @sql nvarchar(4000);
Declare @totalRecord int;
--計算總記錄數
if (@SqlWhere='' or @sqlWhere=NULL)
set @sql = 'select @totalRecord = count(*) from ' + @TableName
else
set @sql = 'select @totalRecord = count(*) from ' + @TableName + ' where ' + @sqlWhere
EXEC sp_executesql @sql,N'@totalRecord int OUTPUT',@totalRecord OUTPUT--計算總記錄數
--計算總頁數
select @TotalPage=CEILING((@totalRecord+0.0)/@PageSize)
if (@SqlWhere='' or @sqlWhere=NULL)
set @sql = 'Select * FROM (select ROW_NUMBER() Over(order by ' + @OrderField + ') as rowId,' + @FIElds + ' from ' + @TableName
else
set @sql = 'Select * FROM (select ROW_NUMBER() Over(order by ' + @OrderField + ') as rowId,' + @FIElds + ' from ' + @TableName + ' where ' + @SqlWhere
--處理頁數超出范圍情況
if @PageIndex<=0
Set @pageIndex = 1
if @pageIndex>@TotalPage
Set @pageIndex = @TotalPage
--處理開始點和結束點
Declare @StartRecord int
Declare @EndRecord int
set @StartRecord = (@pageIndex-1)*@PageSize + 1
set @EndRecord = @StartRecord + @pageSize - 1
--繼續合成sql語句
set @Sql = @Sql + ') as ' + @TableName + ' where rowId between ' + Convert(varchar(50),@StartRecord) + ' and ' + Convert(varchar(50),@EndRecord)
Exec(@Sql)
---------------------------------------------------
If @@Error <> 0
Begin
RollBack Tran
Return -1
End
Else
Begin
Commit Tran
Return @totalRecord ---返回記錄總數
End
end
http://www.cnblogs.com/evernory/archive/2006/11/15/561254.Html