分页储存过程

/*
  函数名称: GetRecordFromPage
  函数功能: 获取指定页的数据
  参数说明:
 @tblName       包含数据的表名
 @PKName       关键字段名
 @strGotFields 要获取的字段
 @PageSize      每页记录数
 @PageIndex     要获取的页码
 @OrderType     排序类型, 0 - 升序, 1 - 降序
 @strWhere      查询条件 (注意: 不要加 where)
 @isCount 是否取得记录条数 , 0 - 不取 , 1 - 获取
 @strSort 排序字段
*/
CREATE PROCEDURE GetRecordFromPage
    @tblName      varchar(255),        -- 表名
    @PKName      varchar(255),        -- 字段名
    @strGotFields varchar(1000) = '*' ,  --查询字段名
    @PageSize     int = 10,             -- 页尺寸
    @PageIndex    int = 1,              -- 页码
    @OrderType    bit = 0,              -- 设置排序类型, 非 0 值则降序
    @strWhere     varchar(2000) = '' ,  -- 查询条件 (注意: 不要加 where)
    @isCount bit = 1,   --取得记录条数
    @strSort varchar(255) = ''  --排序字段
AS
declare @strSQL   varchar(6000)       -- 主语句
declare @strTmp   varchar(1000)        -- 临时变量
declare @strOrder varchar(500)          -- 排序类型
declare @strCount varchar(1000)
declare @fldName varchar(255)
declare @sortName varchar(255)
declare @countSQL varchar(1000)

set @fldName = @PKName
if @strSort != ''
begin
    set @sortName = @strSort
end
else
begin
    set @sortName = @PKName
end

if @isCount = 1
begin
 if @strWhere != ''
 begin
     set @countSQL = 'select count(' + @fldName + ') from ' + @tblName  + ' where ' + @strWhere
 end
 else
     begin
     set @countSQL = 'select count(' + @fldName + ') from ' + @tblName
     end
 exec (@countSQL)
 return
end

else
begin
    if @OrderType != 0
    begin
    set @strTmp = '<(select min'
    set @strOrder = ' order by ' + @sortName + ' desc'
    end
    else
    begin
    set @strTmp = '>(select max'
    set @strOrder = ' order by ' + @sortName +' asc'
    end

    set @strSQL = 'select top ' + str(@PageSize) + @strGotFields + '  from '
    + @tblName + ' where ' + @fldName + '' + @strTmp + '('
    + @fldName + ') from (select top ' + str((@PageIndex-1)*@PageSize) + ' '
    + @fldName + ' from ' + @tblName + '' + @strOrder + ') as tblTmp)'
    + @strOrder

    if @strWhere != ''
    set @strSQL = 'select top ' + str(@PageSize) + @strGotFields + '  from '
        + @tblName + ' where ' + @fldName + '' + @strTmp + '('
        + @fldName + ') from (select top ' + str((@PageIndex-1)*@PageSize) + ' '
        + @fldName + ' from ' + @tblName + ' where ' + @strWhere + ' '
        + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder

    if @PageIndex = 1
    begin
    set @strTmp = ''
    if @strWhere != ''
        set @strTmp = ' where (' + @strWhere + ')'

    set @strSQL = 'select top ' + str(@PageSize) + @strGotFields + '  from '
        + @tblName + '' + @strTmp + ' ' + @strOrder
    end

    exec (@strSQL)
end
GO

原文地址:https://www.cnblogs.com/yangjunwl/p/980221.html