一个分页存储过程 求大家分解分解

来源:互联网 发布:python qqbot 编辑:程序博客网 时间:2024/04/29 20:28
--分页
alter           PROCEDURE [dbo].[NewListPage2](
@tblName nvarchar(500),        ----要显示的表或多个表的连接
@fldName nvarchar(2000) = '*',        ----要显示的字段列表
@pageSize int = 10,                 ----每页显示的记录个数
@page int = 1,        ----要显示那一页的记录
@pageCount int = 0 output,        ----查询结果分页后的总页数
@Counts int = 1 output,        ----查询到的记录数
@fldSort nvarchar(100) = null,        ----排序字段列表或条件
@Sort bit = 0,        ----排序方法,0为升序,1为降序
@strCondition nvarchar(1000) = null,----查询条件,不需where
@ID nvarchar(50)----主表的主键
)
AS
SET NOCOUNT ON


 Declare   @s   nvarchar(4000) --存放查询处理语句   
 Declare   @sqlSort   nvarchar(1000)     ----存放临时生成的排序条件   
 Declare   @pg1   int,@pg2   int       ----要移动的记录数    
    
  --对传入的参数进行规范处理   
  set   @strCondition=isnull('   where   '+@strCondition,' ')   
  if   isnull(@pageSize,0)<=0   set   @pageSize=10   
  if   isnull(@page,0)<=0   set   @page=1   
 
    
  --如果未取得总页数,则取总页数   
  if isnull(@pageCount,0)<=0   
  begin   
  set   @s='select   @Counts= count(distinct('+@ID+'))   from   '+@tblName+@strCondition   
  exec   sp_executesql   @s,N'@Counts   int   out   ',@Counts   out   
    
  --取得分页总数   
  set   @pageCount=(@Counts+@pageSize-1)/@pageSize   
  end   
  
  --如果要显示的页数超过总页数,纠正要显示的页数为最后一页   
  if   @page>@pageCount   set   @page=@pageCount   
  if   @page=1 --如果只有一页,直接显示即可   
  begin   
  set   rowcount   @pageSize   
  exec('select   '+@fldName+'   from   '+@tblName+@strCondition+'  group by '+@ID+'  '+@fldSort)
  end   
  else if @page>1  
  begin   
 set @pg1=@page*@pageSize
 set @pg2=@pg1-@pageSize   
 select @s='select   '+@ID+' as inerid   into   #id   from   '+@tblName+@strCondition+'  group by '+@ID+'   '+@fldSort
 +';set   rowcount   @pg2;delete   from   #id'   
 +';select   '+@fldName+'   from   '+@tblName   
 +@strCondition  
 +case   when   @strCondition=''   then   '   where   '   else   '   and   '   end   
 +'   exists(select   *   from   #id   where   inerid='+@ID+')' +'  group by '+@ID+'   '   
 +@fldSort

 set   rowcount   @pg1 
print @pg2 
print @s
 exec   sp_executesql   @s,N'@pg2   int',@pg2 
  end   
    


  ------恢复系统设置-----   
  set   rowcount     0   
  SET   NOCOUNT   OFF
GO

这个存储过程执行起来特快 效率刚刚的,可是不怎么看的懂。
请看的懂得给讲讲原理,