從網上看了很多
分頁的
存儲過程,沒有發現一個所有表通用的!也許有更高的招,只是我自己不知道而已,特發此貼,以集思廣益。
我先發一個我自己寫的通用分頁存儲過程,希望前輩、哥哥姐姐、弟弟妹妹們批評指正,本人不勝感激。
代碼
--@Columns 要得到的列
--@TableName 表名(可做聯合查詢)
--@Condition 查詢條件
--@OrderBy 排序規則
--@PageNum 第幾頁
--@PageSize 每頁有多少務記錄
--@PageCount 輸出總頁數
--@RecordCount 輸出總記錄數
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