视图工作缓慢,我必须使用select into temp表吗?

时间:2011-04-18 05:33:32

标签: sql tsql sql-server-2008 sql-optimization

所以我遇到了一个严重的麻烦,因为我的上一次查询执行时间是8分钟,以获得2500个节点。它只是其他两个观点的组合。

第一种观点是:

SELECT
   RecTime, SQL AS str, ID, 
   ROW_NUMBER() OVER(ORDER BY RecTime,ID) AS rwnb 
FROM         
   (SELECT
       A.RecTime, X.SQL, X.ID
    FROM 
       dbo.EventView AS A 
    CROSS JOIN
       dbo.Incident AS X
    WHERE      
       (PATINDEX('%' + A.Col + '%', X.SQL) > 0)) AS INC

1秒和1600个节点

第二种观点是:

SELECT     
   D.RecTime, D.Event, D.ID, CAST(CASE WHEN X.[Value] IS NULL THEN 0 ELSE X.[Value] END AS bit) AS Value
FROM         
   dbo.XDependencedEvents AS D 
INNER JOIN
    dbo.EventView AS X ON X.Col = D.Event 
                          AND D.RecTime BETWEEN X.RecTime AND X.ChangedDate

3秒执行时间和2100个节点

并且最终视图是

SELECT 
    X.[Rectime], X.[ID], X.[str], D.[Event], D.[Value],X.[rwnb] 
FROM 
    [XDependencedIncidents] AS X
INNER JOIN [XEventStates] AS D ON X.[Rectime] = D.[Rectime]
                                  AND X.[ID] = D.[ID]

8分钟和2500个节点。

我甚至使用RowNumber AS rwnb来加速处理视图,但它仍然非常慢。我必须在前2个视图中使用select into temp表吗?或者我在这里弄错了什么?

最终目的是在“事件”发生变化时为每个“事件”的某些“组”获取值

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT X.[Rectime] , X.[ID] , X.[str], D.[Event], D.[Value],X.[rwnb] 
FROM [XDependencedIncidents] AS X
INNER JOIN [XEventStates] AS D ON X.[ID] = D.[ID]
WHERE X.[Rectime] = D.[Rectime]

如果它也慢。检查XEventStates Indexing

答案 1 :(得分:0)

我奇怪的解决方案是使用RowNumber,例如修改第二个和最后一个视图,如:

SELECT     D.RecTime, D.Event, D.ID
,CAST(CASE WHEN X.[Value] IS NULL THEN 0 ELSE X.[Value] END AS bit) AS Value
,ROW_NUMBER() OVER(ORDER BY D.RecTime,D.ID) AS rwnb 
FROM         dbo.XDependencedEvents AS D 
    INNER JOIN
    dbo.EventView AS X 
        ON X.Col = D.Event 
        AND D.RecTime BETWEEN X.RecTime AND X.ChangedDate

SELECT X.[Rectime] , X.[ID] , X.[str], D.[Event], D.[Value],X.[rwnb], D.[rwnb]
FROM [XDependencedIncidents] AS X
INNER JOIN [XEventStates] AS D ON X.[ID] = D.[ID]
AND X.[Rectime] = D.[Rectime]

您如何看待这种奇怪的优化方法?如果有的话,我真的想要一个更好的解决方案。

顺便说一句,是的,从8分钟开始添加行号 - > 5秒。