--@Columns 要得到的列
--@TableName 表名(可做聯(lián)合查詢)
--@Condition 查詢條件
--@OrderBy 排序規(guī)則
--@PageNum 第幾頁
--@PageSize 每頁有多少務(wù)記錄
--@PageCount 輸出總頁數(shù)
--@RecordCount 輸出總記錄數(shù)
Create Procedure proc_CurrencyPage
(
@Columns varchar(max),
@TableName varchar(max),
@Condition varchar(max),
@OrderBy varchar(max),
@PageNum int,
@PageSize int,
@PageCount int output,
@RecordCount bigint output
)
AS
DECLARE @Sql nvarchar(max);
Set @Sql = 'Select @CountOut = Count(*) From ' + @TableName + ' Where ' + @Condition;
EXEC sp_executesql @Sql,N'@CountOut INT OUTPUT',@CountOut = @RecordCount OUTPUT;
Set @PageCount = @RecordCount / @PageSize;
IF(@RecordCount % @PageSize > 0) Set @PageCount = @PageCount + 1;
IF(@PageNum < 1) Set @PageNum = 1;
IF(@PageNum > @PageCount) Set @PageNum = @PageCount;
Declare @BRowNum int,@ERowNum int;
Set @BRowNum = (@PageNum - 1) * @PageSize;
Set @ERowNum = @BRowNum + @PageSize;
Set @Sql =
'Select * From (
Select '+@Columns+', ROW_NUMBER() Over(Order By ' + @OrderBy + ') As RowNum
From ' + @TableName + '
Where ' + @Condition + '
) as TempT
Where RowNum > ' + Convert(varchar(10),@BRowNum) + '
And
RowNum <= ' + Convert(varchar(10),@ERowNum) + '
Order By ' + @OrderBy;
Exec(@Sql);
GO
--測試:
Declare @Columns varchar(max)
Declare @TableName varchar(max)
Declare @Condition varchar(max)
Declare @OrderBy varchar(max)
Declare @PageNum int
Declare @PageSize int
Declare @PageCount int
Declare @RecordCount bigint
set @Columns = 'ID,ReportID,ReportCondition'
set @TableName = '[PSYT_TS_ReportSort]'
set @Condition = 'ReportSort = ''Z'''
set @ORDERBY = 'ID'
set @PageNum = 2
set @PageSize=20
Exec proc_CurrencyPage @Columns,@TableName,@Condition,@ORDERBY,@PageNum,@PageSize,@PageCount output,@RecordCount output