如何在SQL Server 2012中加快缓慢的更新查询

时间:2015-11-04 16:39:02

标签: sql sql-server tsql

我有一个工作正常的更新查询,但它太慢了,需要2分钟才能完成。还有其他方法可以编写此查询以加快速度吗?这是我的代码谢谢:

UPDATE #tmpIMDS 
SET 
    ModelFileName = b.ModelFileName,    
    SendEMail = b.SendEMail 
FROM 
(
    SELECT DISTINCT 
        IMDSConversionReportData.ModelNumber,
        ModelFileName,
        'Send Email' AS SendEmail       
    FROM 
        IMDSConversionReportData,           
        (
            SELECT DISTINCT 
                ModelNumber,
                Max(DateAdded) AS DateAdded             
            FROM 
                IMDSConversionReportData            
            GROUP BY 
                ModelNumber) a      
            WHERE 
                IMDSConversionReportData.ModelNumber = a.ModelNumber
                AND IMDSConversionReportData.DateAdded = a.DateAdded 
        ) b
        WHERE ModelID = b.ModelNumber

1 个答案:

答案 0 :(得分:2)

您可以生成IMDSConversionReportData来识别每DateAddedModelNumber,而不是按row_number表两次以获得DateAddedModelNumber}列。

当您只选择一个distinct无意义的非聚合列时,同时删除group by

试试这个

;WITH cte
     AS (SELECT *,
                'Send Email'  AS SendEmail,
                Row_number()OVER(partition BY ModelNumber ORDER BY DateAdded DESC) AS rn
         FROM   IMDSConversionReportData)
UPDATE t
SET    ModelFileName = c.ModelFileName,
       SendEMail = c.SendEMail
FROM   #tmpIMDS t
       INNER JOIN cte c
               ON t.ModelID = c.ModelNumber 
Where Rn = 1 

注意:始终使用正确的INNER JOIN语法连接两个表而不是旧式逗号分隔连接。我们总是发现INNER Join语法更强可读。将过滤器单独保留在Where子句