在分页临时表中获取索引查找而不是扫描?

时间:2014-07-03 16:48:27

标签: sql sql-server performance sql-execution-plan

我已经创建了一个临时表来测试intindex上的主键。

当我select * from #TmpDashboard where intindex = 1时,我得到索引搜索。

但是当我应用分页公式时,我会得到索引扫描,这会导致性能问题。

Declare @Currentpage      INT = 1
      ,@Pagesize         INT = 10

select * from #TmpDashboard 
WHERE  (@Pagesize = 0 OR (intIndex BETWEEN ((@CurrentPage - 1) * @PageSize) + 1 AND (@CurrentPage * @PageSize))) --gives index scan

如何将上述公式转换为索引搜索。

2 个答案:

答案 0 :(得分:1)

WHERE子句中的“OR”导致扫描,因为它使语句不确定。我建议设置第二组变量,用于简化查询,如下所示:

 Declare @Currentpage      INT = 1
      ,@Pagesize         INT = 10;

declare @start int = Case when @pagesizee = 0 then 0 else ((@CurrentPage - 1) * @PageSize) + 1 end
, @end int = case when @pagesize > 0 then @CurrentPage * @PageSize else (select max(intindex) from #tmpdashboard) end

select * from #TmpDashboard 
WHERE  intindex between @start and @end

答案 1 :(得分:0)

create table #TmpDashboard (intindex int primary key)
select * from #TmpDashboard where intindex = 1
Declare @Currentpage INT, @Pagesize INT;
select  @Currentpage= 1, @Pagesize = 10;

select * from #TmpDashboard 
WHERE  intIndex BETWEEN ((@CurrentPage - 1) * @PageSize) + 1 AND (@CurrentPage * @PageSize)
drop table #TmpDashboard