2011-09-23 64 views
1

我的分页方法效率不高,因为它会调用相同的查询两次,因此会加倍查询时间。我目前调用1个查询,连同5个表格一起使用XML搜索查询,以允许从ASP.net传递列表。然后,我需要调用完全相同的查询,除了用Count(row)来获取记录数量SQL + ASP.Net高效分页

为例(我已删除的比特,使其更易于阅读)

主查询:

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 
) 

回答

1

你可以选择你的大查询的结果到一个临时表,那么你就可以查询该表中的行数和拔出你需要的行。

要做到这一点,添加(SELECT语句之后和之前的距离)

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 
+0

为什么你需要tmptable? - 你能不能把计数(*)放在第一个选择中,这样每一行都有计数呢? – michael

+0

不,因为要做一个'COUNT(*)'你必须做一个'GROUP BY'聚合。 – cjk

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 

希望这有助于

+0

你不能叫CTE两次,所以最后的陈述将失败。 – cjk

+0

ahh ok,所以根据你的建议,你需要在选择之前用结果填充临时表,这样你可以从中选择两次..很有意义。 – rabs