This SQL query took 38 minutes to delete just 10K of rows. How can I optimize it?
Index already exists for CREATEDATE
from table2
.
declare @tmpcount int
declare @counter int
SET @counter = 0
SET @tmpcount = 1
WHILE @counter <> @tmpcount
BEGIN
SET ROWCOUNT 10000
SET @counter = @counter + 1
DELETE table1
FROM table1
JOIN table2
ON table2.DOC_NUMBER = table1.DOC_NUMBER
AND table2.DOC_YEAR = table1.DOC_YEAR
WHERE YEAR(CREATEDDATE) BETWEEN 2007 and 2009
IF @@ROWCOUNT = 0
BREAK
END