百万级分页存储过程

本文介绍了一个SQL分页存储过程的实现方法,通过使用T-SQL动态执行语句来根据传入的参数进行分页查询。该存储过程能够根据查询条件、页面大小和当前页码返回指定范围内的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天看到有人在论坛谈分页存储过程.小弟不才..自己写了个存储过程.代码如下:

/*------------------------------------------------------------------  
  作者:范亮 
  日期:2007-11-20  
  功能:根据条件查询环境检查结果信息  
 
      
--------------------------------------------------------------------*/  


ALTER   procedure [dbo].[Get_QuestionByConditionPage]  
(  
  @xCondition   nvarchar(max),   --查询条件  
  @xPageSize   int,       --每页数据行数  
  @xPagePos    int output,    --当前页码  
  @xTotalRowCount int output    --总数据行数  
)  
as  
begin  
  declare @startRowNo int    --页起始行号  
  declare @endRowNo int     --页结束行号  
  declare @sql nvarchar(max)  --查询语句  
  --获取总的记录数  
  set @sql = N'  
  select @xTotalRowCount = count(*)  
  from   
  (  
select 
 b.fTypeTitle,
 a.fQuestionId,
 a.fTypeID,
 a.fTitle,
 a.fInformation,
 a.fAnswer,
 a.fCreatetime,
 a.fIP,
 a.fOperater
from TQuestionInfo a
 left join
TQuestionTypeInfo b
on a.fTypeID=b.fTypeID
 ) as t   
  where 1 = 1 ' + @xCondition 

  exec sp_executesql @sql, N'@xTotalRowCount int output', 
    @xTotalRowCount output  
  if @xPagePos < 0  
 set @xPagePos = 0  

  if @xPageSize <= 0  
  begin  
 --不分页  
 set @startRowNo = 1  
 set @endRowNo = @xTotalRowCount  
 set @xPagePos = 0  
  end  
  else  
  begin  
 --分页  
 set @startRowNo = @xPagePos * @xPageSize + 1  
 set @endRowNo = (@xPagePos + 1) * @xPageSize  
  end  
  
  if @startRowNo > @xTotalRowCount and @xTotalRowCount <> 0  
  begin  
 --超出最大页码,重新计算当前页、开始和结束位置,使当前页为可用的最后一页  
 if (@xTotalRowCount > 0) and (@xTotalRowCount % @xPageSize = 0)  
   set @xPagePos = @xTotalRowCount / @xPageSize - 1  
 else  
   set @xPagePos = @xTotalRowCount / @xPageSize  
  
 set @startRowNo = @xPagePos * @xPageSize + 1  
 set @endRowNo = (@xPagePos + 1) * @xPageSize;  
  end 
  
  set @sql = N'   
  select   
 fQuestionId,
 fTypeTitle,
 ftitle,
 fInformation,
 fAnswer,
 fCreatetime,
 fIP,
 fOperater
  from  
 (  
   select  
  row_number() over(order by fQuestionId asc) as rownum,   
  *  
   from  
  (  
 select 
  b.fTypeTitle,
  a.fQuestionId,
  a.fTypeID,
  a.fTitle,
  a.fInformation,
  a.fAnswer,
  a.fCreatetime,
  a.fIP,
  a.fOperater
  from TQuestionInfo a
  left join
  TQuestionTypeInfo b
  on a.fTypeID=b.fTypeID
 ) as t1
 where 1 = 1 ' + @xCondition + '  
 ) as t2  
  where rownum between ' + convert(varchar, @startRowNo) + ' and ' + convert(varchar, @endRowNo) + ' '  
  set @sql = @sql + ' order by fQuestionId asc '   
  exec(@sql) 
end 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值