基于Select Max 的分页

来源:互联网 发布:php入门到精通pdf下载 编辑:程序博客网 时间:2024/05/17 19:18

基于Select Max 的分页,据网上的资料,说是最快的,于是,就添上来备用

Create  PROCEDURE XPage

@tblName   varchar(255),       -- 表名

@strGetFields varchar(1000) = '*',  -- 需要返回的列

@fldName varchar(255)='',      -- 排序的字段名: 必需是唯一的并且只能有一个

@PageSize   int = 10,          -- 页尺寸

@PageIndex  int = 1,           -- 页码

@doCount  bit = 0,   -- 返回记录总数, 非 0 值则返回

@OrderType bit = 0,  -- 设置排序类型, 非 0 值则降序

@strWhere  varchar(1500) = ''  -- 查询条件 (注意: 不要加 where)

AS

declare @strSQL   varchar(5000)       -- 主语句

declare @strTmp   varchar(110)        -- 临时变量

declare @strOrder varchar(400)        -- 排序类型

 

If @doCount != 0

  begin

    If @strWhere !=''

     set @strSQL = 'select count(*) as Total from [' + @tblName + '] where '+@strWhere

    Else

     set @strSQL = 'select count(*) as Total from [' + @tblName + ']'

    End 

--以上代码的意思是如果@doCount传递过来的不是0,就执行总数统计。以下的所有代码都是@doCount为0的情况

Else

  begin

   If @OrderType != 0  --如果@OrderType不是0,就执行降序,这句很重要!

 begin

      set @strTmp = '<(select min'

   set @strOrder = ' order by [' + @fldName +'] desc'

 End

   Else

 begin

      set @strTmp = '>(select max'

      set @strOrder = ' order by [' + @fldName +'] asc'

 End

 

   If @PageIndex = 1 --如果是第一页就执行以上代码,这样会加快执行速度

 begin

      If @strWhere != ''  

         set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ '  from [' + @tblName + '] where ' + @strWhere + ' ' + @strOrder

       Else

          set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ '  from ['+ @tblName + '] '+ @strOrder

 

 End

   Else --以下代码赋予了@strSQL以真正执行的SQL代码

 begin
         If @strWhere = ''
   set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ '  from ['

       + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['+ @fldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'+ @strOrder
  Else

       set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ '  from ['

           + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['

           + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['

           + @fldName + '] from [' + @tblName + '] where ' + @strWhere + ' '

           + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder

   End

 End  

exec (@strSQL)

原创粉丝点击