如何使用Filters和Pagination优化SQL Server查询?

时间:2018-02-08 13:50:33

标签: sql-server performance sql-server-2008 query-optimization

我需要针对此查询的优化建议(无权访问修改索引),出于安全原因我省略了一些变量名称,但这基本上是我的查询,它在我使用时波动大约300到900毫秒完成c#它快一点,但我希望低于100毫秒。 SQL SERVER 2008

任何想法?

CREATE PROCEDURE [dbo].MyProcedure (  
    PARAMETERS!!!
  AS   
 BEGIN  

SET NOCOUNT ON;   


  create  TABLE #SearchTable  
  (  
  TEMP TABLE PARAMETERS!!!
  )  

   insert into #SearchTable (COLUMNS!!!)  

    SELECT DISTINCT  MYDATA!!!
      FROM VIEW!!!  
     WHERE ID =    @ID    
            AND ((( @Variable is  null)            or (VARIABLE LIKE @Variable + '%' ) )
            AND ((( @Variable is  null)            or (VARIABLE LIKE @Variable + '%' ) )
            AND ((( @Variable is  null)            or (VARIABLE LIKE @Variable + '%' ) )
            AND ((( @Variable is  null)            or (VARIABLE LIKE @Variable + '%' ) )
            AND ((( @Variable is  null)            or (VARIABLE LIKE @Variable + '%' ) )
            AND ((( @Variable is  null)            or (VARIABLE LIKE @Variable + '%' ) )



 declare @sql NVARCHAR(max)  
 set @sql = '  
  select * from (  
   select ROW_NUMBER() over (order by '+ @orderBy +') as RowNumber,*   
    from #SearchTable) table
    WHERE (RowNumber > '+ cast(((@CurrentPage -1) * @PageSize) as varchar(max)) +'  
  AND RowNumber <= '+ cast( ((@CurrentPage) * @PageSize) as varchar(max)) +'  
OR ' +  cast( (@PageSize) as varchar(max)) +' = 0)' 

 EXEC sp_executesql @sql

 --exec(@sql)

  select @totalCount = count(*) from #SearchTable  
   print @totalCount  

1 个答案:

答案 0 :(得分:0)

抱歉......需要编辑...这就是你得到的东西&#34;头顶&#34; ......

离开头顶进行分页,你已经有了动态sql,所以只要你确保你的项目顺序得到保留就可以'select TOP ' + CAST(@NumberItemsPerPage AS nvarchar(10)) + ' * FROM...WHERE [RowCount] >= ' + CAST((@NumberItemsPerPage * @PageCount) AS nvarchar(10)) + ' AND [RowCount] < ' + CAST((@NumberItemsPerPage * @PageCount)+@NumberItemsPerPage AS nvarchar(10)) ...那应该是给你分页方面。

至于表演,欢迎来到试验和错误的精彩世界。索引,键和架构都发挥作用所以我最好的建议是尝试不同的查询方法,使用查询分析器查看是否有任何其他索引可以工作... 戴夫