查询在sql server上创建加载

时间:2016-02-23 10:59:20

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

我做了一个查询

Select         
-- Generate the row number        
ROW_NUMBER() over(order by MenuOrder) as 'rownum',        
-- get the minimum data from query        
(Select top 1 ROW_NUMBER()over(order by MenuOrder)          
from SitePage where ActiveFlag='true' AND SiteId=1083 and LanguageId=159 AND ChildOf=0 order by MenuOrder asc) as 'min',        
-- get the maximum data from query        
(Select top 1 ROW_NUMBER()over(order by MenuOrder)  from SitePage where ActiveFlag='true' and LanguageId=159 AND SiteId=1083 AND ChildOf=0         
order by MenuOrder desc) as 'max',        
-- get rest of all details        
*,(case when exists(select *from SitePage where ChildOf = AP.SitePageId and ActiveFlag =1  ) then 'Y' else 'N' end) as [Type]  from SitePage AP 
where ActiveFlag=1 AND SiteId=1083 AND ChildOf=0 and LanguageId=159 order by MenuOrder

之后,当我看到查询性能时,需要花费很多时间来执行,这会在sql server上造成负载,导致服务器意外关闭

此处为total_elapsed_time_in_Seconds:61480

如何减少total_elapsed_time_in_Seconds

1 个答案:

答案 0 :(得分:1)

您可以通过重构来改进查询,例如,您正在执行完整查询以获得最小ROW_NUMBER(),这将始终为1.同样,不需要单独的子查询来获得最大值,由于过滤器完全相同,因此您只需在主查询中使用COUNT(*) OVER()

接下来应该做的就是不使用SELECT *并且只返回您需要的列,即使这些列都是still good practise to state all the columns

SELECT  RowNum = ROW_NUMBER() OVER(ORDER BY ap.MenuOrder),
        [Min] = 1,
        [Max] = COUNT(*) OVER(),
        [Type] = ISNULL(t.[Type], 'N'),
        ap.Column1,
        ap.Column2,
        ap.Column3
FROM    SitePage AS ap 
        OUTER APPLY
        (   SELECT  TOP 1 'Y'
            FROM    SitePage AS ap2
            WHERE   ap2.ChildOf = ap.SitePageID
            AND     ap2.ActiveFlag = 1
        ) AS t ([Type])
WHERE   ap.ActiveFlag = 1 
AND     ap.SiteId = 1083 
AND     ap.ChildOf = 0 
AND     ap.LanguageId = 159 
ORDER BY ap.MenuOrder;

这应该已经提高了性能,但索引可能会进一步改善这一点。在不知道您的数据的情况下很难知道最佳索引是什么,但一个好的起点是在SSMS中启用“显示实际执行计划”,然后这将为您建议索引。这绝不是一门精确的科学,但它应该让你开始朝着正确的方向前进。