订购时的性能

时间:2014-04-09 11:53:25

标签: sql sql-server-2008

对于以下脚本:

DECLARE @StartDate DATETIME,
        @EndDate DATETIME,
        @SearchSt INT

SET @StartDate = '2014-02-01'
SET @EndDate = '2014-02-20'
SET @SearchSt = 2;

WITH DSAEvent
AS
(
 SELECT ROW_NUMBER() OVER
        (
         PARTITION BY e.TT_TAG_ID 
             ORDER BY e.TT_TAG_ID,
                      e.DSA_Event_Date,
                      e.DSA_Time_In,
                      e.DSA_Time_Out,
                      e.TAG_Inter_DSA_Seq_No
        ) AS rn,
        e.EventID, e.TT_TAG_ID, e.DSA_ID, e.DSA_Purpose_ID, e.DSA_Time_In,
        e.DSA_Time_Out, e.DSA_Duration, e.Sh_DSA_Event_Record_Type,
        e.TAG_Inter_DSA_Seq_No, 
        ISNULL((
                 SELECT CASE
                            WHEN e.DSA_Purpose_ID = 3 THEN ISNULL(T_No, 0)
                            ELSE -1
                        END
                   FROM DSAs
                  WHERE St_ID = @SearchSt
                    AND DSA_ID = e.DSA_ID
               ), -1) AS T_No
   FROM SH_DSA_EVENT_WORKING e
  WHERE e.Store_ID = @SearchSt
    AND e.DSA_Event_Date >= @StartDate
    AND e.DSA_Event_Date <= @EndDate
    AND e.Sh_ID IS NULL
)

 SELECT p.TT_TAG_ID, p.DSA_ID, p.DSA_Purpose_ID, p.DSA_Time_In,
        p.DSA_Time_Out, p.DSA_Duration, p.Sh_DSA_Event_Record_Type,
        p.TAG_Inter_DSA_Seq_No, p.Till_No,
        ABS(DATEDIFF(
                second,
                ISNULL(n.DSA_Time_In, '2000-01-01 00:00:00'),
                ISNULL(p.DSA_Time_Out, '2000-01-01 00:00:00'))
           ), 
        td.TAG_Asset_Type_ID, p.EventID
   FROM DSAEvent p
        LEFT JOIN DSAEvent n ON p.rn = n.rn - 1 AND p.TT_TAG_ID = n.TT_TAG_ID
        LEFT JOIN TAG_DETAIL td ON td.TT_TAG_ID = p.TT_TAG_ID
  WHERE ISNULL(td.St_ID, @SearchSt) = @SearchSt
  ORDER BY td.TT_TAG_ID, p.DSA_Time_In, p.DSA_Time_Out,
           p.TAG_Inter_DSA_Seq_No, p.rn

这似乎需要永远运行。我已将其缩小到最终的ORDER条款。

如果我注释掉ORDER子句,我会在13秒内返回741594行。如果我让脚本使用ORDER子句运行,它将运行超过13个小时。

我错过了什么,或者如何弄清楚造成延误的原因?

2 个答案:

答案 0 :(得分:1)

问题似乎是ORDER BY td.TT_TAG_ID。 如果LEFT JOIN为列提供了如何排序的空值?

您可以尝试ORDER BY p.TT_TAG_ID

答案 1 :(得分:0)

您必须简化此测试。拉出连接并选择标准和度量。一次添加一个项目并重新测量以查看问题所在。另外,研究执行计划