set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
-- =============================================
-- Author: <lancanfei>
-- Create date: <2008-2-23>
-- Description: <海量數據分頁存儲過程>
-- =============================================
ALTER PROCEDURE [dbo].[sp_GetRecordListByPage]
@tblName nvarchar(200), -- 表名
@fldName nvarchar(200), -- 字段名
@pageSize int = 10, -- 頁尺寸
@pageIndex int = 1, -- 頁碼
@IsReCount bit = 0, -- 返回記錄總數, 非 0 值則返回
@fldSort nvarchar(100) = null, ----排序字段列表或條件
@Sort bit = 0, -- 設置排序類型, 非 0 值則降序
@strWhere nvarchar(1000) = '', -- 查詢條件 (注意: 不要加 where)
@ID nvarchar(50), ----主表的主鍵
@pageCount int = 1 output, ----查詢結果分頁後的總頁數
@Counts int = 1 output ----查詢到的記錄數
AS
declare @strSQL nvarchar(4000) -- 主語句
declare @strTmp nvarchar(4000) ----存放取得查詢結果總數的查詢語句
declare @sqlSort nvarchar(400) -- 排序類型
--------生成查詢語句----------此處@strTmp爲取得查詢結果數量的語句
if (@strWhere is null or @strWhere='') --沒有設置顯示條件
begin
set @strTmp = 'select @Counts=Count(' + @ID + ') FROM '+@tblName
end
else
begin
set @strTmp = 'select @Counts=Count(' + @ID + ') FROM '+@tblName + ' where ' + @strWhere
end
----取得查詢結果總數量----
exec sp_executesql @strTmp,N'@Counts int out ',@Counts out
if @IsReCount = 0
begin
----取得分頁總數----
if @Counts <= @pageSize
set @pageCount = 1
else
begin
set @pageCount = (@Counts / @pageSize) + 1
if(@Counts % @pageSize=0)
set @pageCount =@pageCount -1
end
--------生成排序方法---------
if @Sort=0 --升序
begin
set @strTmp = '>(select max'
if not(@fldSort is null or @fldSort='')
set @sqlSort = ' Order by ' + @fldSort
else
set @sqlSort = ' Order by ' + @ID
end
else --降序
begin
set @strTmp = '<(select min'
if not(@fldSort is null or @fldSort='')
set @sqlSort = ' Order by ' + @fldSort + ' DESC'
else
set @sqlSort = ' Order by ' + @ID + ' DESC '
end
----拼接查詢語句----
if @PageIndex = 1 ------如果是第一頁------
begin
set @strTmp =''
if @strWhere != ''
set @strTmp = ' where ' + @strWhere
set @strSQL = 'select top ' + str(@PageSize) + @fldName +' from ['
+ @tblName + ']' + @strTmp + ' ' + @sqlSort
end
else
begin
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) + @fldName +' from ['
+ @tblName + '] where [' + @ID + ']' + @strTmp + '(['
+ @ID + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @ID + '] from [' + @tblName + '] where ' + @strWhere + ' '
+ @sqlSort + ') as tblTmp) and ' + @strWhere + ' ' + @sqlSort
else
set @strSQL = 'select top ' + str(@PageSize) + @fldName + ' from ['
+ @tblName + '] where [' + @ID + ']' + @strTmp + '(['
+ @ID + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @ID + '] from [' + @tblName + ']' + @sqlSort + ') as tblTmp)'
+ @sqlSort
end
exec (@strSQL)
end