SQL + ASP.Net高效的分页

时间:2011-09-23 06:10:09

标签: c# asp.net sql sql-server-2008

我的分页方法效率低,因为它调用相同的查询两次,因此查询时间加倍。我目前调用1个查询加入约5个表和XML搜索查询以允许从ASP.net传递List ..然后我需要调用完全相同的查询,除了使用Count(行)来获取记录数量< / p>

例如(我删除了一些位以便于阅读)

主要查询:

WITH Entries AS (
  select row_number() over (order by DateReady desc)
  as rownumber, Columns...,

 from  quote

 join geolookup as Pickup on pickup.geoid = quote.pickupAddress

 where 
     quote.Active=1
     and //More 
 )
 select * from entries 
 where Rownumber between (@pageindex - 1) * @pagesize + 1 and @pageIndex * @pageSize
 end

计数查询:

 select count(rowID)        
 from  quote

 join geolookup as Pickup on pickup.geoid = quote.pickupAddress

 where 
     quote.Active=1
     and //More 
 )

2 个答案:

答案 0 :(得分:1)

您可以设置一个输出参数,该参数将保存第一个查询中的行数。

您可以执行类似

的操作
WITH Entries AS (
  select row_number() over (order by DateReady desc)
  as rownumber, Columns...,

 from  quote

 join geolookup as Pickup on pickup.geoid = quote.pickupAddress

 where 
     quote.Active=1
    and //More 
 )

select @rowcount = max(rownumber) from entries

 select * from entries 
 where Rownumber between (@pageindex - 1) * @pagesize + 1 and @pageIndex * @pageSize

希望这有帮助

答案 1 :(得分:1)

您可以将大查询的结果选择到临时表中,然后您可以在此表中查询行号并提取所需的行。

要执行此操作,请添加(在您的select语句之后和from之前)

INTO #tmpTable

然后将您的表格引用为#tmpTable


select row_number() over (order by DateReady desc)  
  as rownumber, Columns...,  
into #tmpTable

 from  quote  

 join geolookup as Pickup on pickup.geoid = quote.pickupAddress  

 where   
     quote.Active=1  
     and //More   
 )  

 SELECT @Count = COUNT(*) FROM #tmpTable

 select * from #tmpTable  
 where Rownumber between (@pageindex - 1) * @pagesize + 1 and @pageIndex * @pageSize