为什么我会获得这种意外的SQL性能提升?

时间:2017-10-17 11:32:40

标签: sql sql-server tsql

这更像是一个测验问题,而不是我在截止日期前的恐慌,但是理解如何/为什么无疑会让我的头脑少一点!

所以我有这个UPDATE语句:

/*** @Table is a TABLE Variable ***/
UPDATE O
SET O.PPTime = T.PPTime
FROM @Table AS [O]
INNER JOIN 
    (SELECT O.OSID, O.STID, DATEDIFF(SECOND, O.StartDateTime, O.EndDateTime) AS [PPTime]
        FROM tblO AS [O]
        INNER JOIN tblS AS [S] ON O.OSID = S.OSID
        INNER JOIN tblE AS [E] ON S.EID = E.EID
        INNER JOIN tblEF AS [EF] ON E.EFID = EF.EFID
        GROUP BY O.OSID, O.STID, O.StartDateTime, O.EndDateTime) AS [T]
ON O.OSID = T.OSID
WHERE O.PPTime IS NULL

执行时间约为12秒。

现在,我在一个小的WHERE语句中添加了一个对用户返回多少行数据没有任何影响:

/*** @Table is a TABLE Variable ***/
UPDATE O
SET O.PPTime = T.PPTime
FROM @Table AS [O]
INNER JOIN 
    (SELECT O.OSID, O.STID, DATEDIFF(SECOND, O.StartDateTime, O.EndDateTime) AS [PPTime]
        FROM tblO AS [O]
        INNER JOIN tblS AS [S] ON O.OSID = S.OSID
        INNER JOIN tblE AS [E] ON S.EID = E.EID
        INNER JOIN tblEF AS [EF] ON E.EFID = EF.EFID
        WHERE O.OSID >= 0       /*** Somehow fixes performance slow down! ***/
        GROUP BY O.OSID, O.STID, O.StartDateTime, O.EndDateTime) AS [T]
ON O.OSID = T.OSID
WHERE O.PPTime IS NULL

执行时间现在不到一秒钟。如果我单独运行两个SELECT语句,它们会在同一时间执行并返回相同的数据。

为什么我会获得这样的性能提升?

1 个答案:

答案 0 :(得分:0)

在查看代码之后,我注意到添加主键和/或索引到表变量完成了诀窍!一个让我记住!