如何使用多个' AND'来优化慢速运行的查询?声明?

时间:2016-07-22 05:38:45

标签: sql sql-server

我试图从数据库(SQL Server)中清除旧记录,该数据库只有一个包含数百万条记录的表格。我使用的查询将永远运行。有可能优化这个吗?

DECLARE @Count INT = -15;
DECLARE @CountThreshold INT = -4;
DECLARE @DeletedRows INT = 0 WHILE @Count <= @CountThreshold BEGIN BEGIN TRANSACTION T1
DELETE [Log]
WHERE [Date] <= DATEADD(d, @Count, getdate())
  AND (windowsIdentity LIKE 'BTA-SL%'
       AND Environment ='')
  SET @Count = @Count + 1;



PRINT 'DELETED '+ CONVERT(VARCHAR(10),@DeletedRows) + ' ROWS ON COUNT - '+ CONVERT(VARCHAR(10),@Count)
COMMIT TRANSACTION T1 END

1 个答案:

答案 0 :(得分:0)

你的while不是util,因为@CountThreshold&lt; @计数。你可以做到这一点:

  DECLARE @CountThreshold INT = -4;

  DELETE [Log]
  WHERE [Date] <=DATEADD(d, @CountThreshold , getdate())
   AND (windowsIdentity LIKE 'BTA-SL%'
   AND Environment ='');

  PRINT 'DELETED '+  CAST(@@ROWCOUNT AS VARCHAR(10)) + ' rows deleted'

  COMMIT TRANSACTION T1 END