优化查询性能以进行更新

时间:2015-10-12 10:54:18

标签: sql sql-server

我有以下查询:我有350万条记录。如何优化查询性能,因此不需要4个小时?

DECLARE @Counter INT=0 --This causes the @@rowcount to be > 0
while @@rowcount>0
BEGIN
    SET rowcount 10000
    update r
   set Comp=t.Comp
  FROM [QlikDataWarehouse].[dbo].[Vente]r with (NOLOCK)
  inner join [QlikDataWarehouse].[dbo].[Budget] t with (index (index_Budget )) 
   on t.[Code Site]=r.[Code Site]
  and t.[Code Rayon] =substring(r.[Code Structure],1,4)
  and t.[Date Time]=convert(date,r.[Date Time])
  WHERE r.[Date Time] >= '2015-01-01 00:0:00.000'

end
SET rowcount 0 

1 个答案:

答案 0 :(得分:1)

这是您的查询:

update r
   set Comp = t.Comp
from [QlikDataWarehouse].[dbo].[Vente]r with (NOLOCK) inner join
     [QlikDataWarehouse].[dbo].[Budget] t)
     on t.[Code Site] = r.[Code Site] and
        t.[Code Rayon] = substring(r.[Code Structure],1,4) and
        t.[Date Time] = convert(date,r.[Date Time])
where r.[Date Time] >= '2015-01-01 00:0:00.000';

优化这将有点挑战。您的问题可能只是更新的记录量。如果是这样,最好的方法是使用select into重新创建表,截断表,然后重新插入行。发生这种情况是因为这些操作比更新所需的所有日志记录和索引更新快得多。

但是,索引可能有效。您可能只是尝试删除index提示,以查看SQL Server是否比优化时更好。我认为最好的索引是:vente([Date Time], [Code Site], [Code Structure])Budget([Code Site], [Code Rayon], Date Time])