Trying to delete records from a table that has 20 million records

52 Views Asked by At

I have this stored procedure that it is not finishing the execution at all. The table TbARIAFLD3_ARIAFLD3Errors has 20 million rows, could you please help me how to execute it faster? The TbARIAFLD3Errors table has 600000+ rows, and other tables aren't that bad but still have thousands of rows.

Could you please help me to execute it faster?

ALTER PROCEDURE [dbo].[SspArchiveDeleteReportInstance]
AS
BEGIN

--------------------------------------------------
SET NOCOUNT ON
--------------------------------------------------

DECLARE @deleteTable TABLE([ReportInstanceId] uniqueidentifier NOT NULL)
Print 'Entered into the Store Procedure'
-- Do an inner join to pick up records that haven't been archived yet
INSERT @deleteTable 
    SELECT DISTINCT TOP 50 TbReportInstance.ReportInstanceId 
    FROM TbReportInstance
    INNER JOIN TbReportInstanceReportUnit ON TbReportInstanceReportUnit.ReportInstanceId = TbReportInstance.ReportInstanceId
    WHERE TbReportInstance.ArchiveFlag = 1
        
Print 'Before First Delete'
-- Delete everything that joins to the delete table
DELETE TbReportInstanceReportUnit 
FROM TbReportInstanceReportUnit
INNER JOIN @deleteTable DT ON TbReportInstanceReportUnit.ReportInstanceId = DT.ReportInstanceId

--Address Files
Print 'Before Large Statement'
DECLARE @deleteTbARIAFLD3Errors TABLE(Id int identity, ARIAFLD3ErrorId uniqueidentifier NOT NULL)
INSERT @deleteTbARIAFLD3Errors 
    select DISTINCT TbARIAFLD3Errors.ARIAFLD3ErrorId
    FROM TbARIAFLD3Errors with (nolock)
    INNER JOIN TbARIAFLD3_ARIAFLD3Errors with (nolock) ON TbARIAFLD3_ARIAFLD3Errors.ARIAFLD3ErrorId = TbARIAFLD3Errors.ARIAFLD3ErrorId
    INNER JOIN TbARIAFLD3 with (nolock) ON TbARIAFLD3.ARIAFLD3Id = TbARIAFLD3_ARIAFLD3Errors.ARIAFLD3Id
    INNER JOIN @deleteTable DT ON TbARIAFLD3.ReportInstanceId = DT.ReportInstanceId
Print '1st Large Statement Completed'

declare @count bigint, @loopCount bigint, @iterator int=1, @var uniqueidentifier
select @count=max(Id) from @deleteTbARIAFLD3Errors
select @count Counts
select @iterator = min(Id) from @deleteTbARIAFLD3Errors
--set @loopCount = @count/10000
select @iterator iterator

    WHILE (@iterator <= @count)
    BEGIN
        select top 1 @var =  ARIAFLD3ErrorId from @deleteTbARIAFLD3Errors DT where DT.Id=@iterator
        DELETE TbARIAFLD3_ARIAFLD3Errors
        FROM TbARIAFLD3_ARIAFLD3Errors where ARIAFLD3ErrorId = @var
        --INNER JOIn @deleteTbARIAFLD3Errors DT on TbARIAFLD3_ARIAFLD3Errors.ARIAFLD3ErrorId=DT.ARIAFLD3ErrorId
        --where DT.Id=@iterator
        
        set @iterator=@iterator+1       
    END
--------------------------------------------------
SET NOCOUNT OFF
--------------------------------------------------
END
0

There are 0 best solutions below