Microsoft Dynamics AX 2012 Batch Job History Delete SQL Script

  This query is tested with Ax 2012

--SQL Script Begins

DECLARE @Count INT

Declare @for_delete INT

Declare @chunk_size INT

SELECT @chunk_size=1000

SELECT @Count = 0

select @for_delete=count(*) from BATCHJOBHISTORY

where BATCHJOBHISTORY.CREATEDDATETIME < (GETDATE()-10)

While (@Count < @for_delete)

BEGIN

SELECT @Count = @Count + @chunk_size

BEGIN TRAN

delete top(@chunk_size) from BATCHJOBHISTORY

where BATCHJOBHISTORY.CREATEDDATETIME < (GETDATE()-10)

delete BATCHHISTORY

where not exists (select RECID from BATCHJOBHISTORY

where BATCHJOBHISTORY.RECID = BATCHHISTORY.BATCHJOBHISTORYID)

delete BATCHCONSTRAINTSHISTORY

where not exists (select RECID from BATCHHISTORY

where BATCHHISTORY.RECID = BATCHCONSTRAINTSHISTORY.BATCHID)

COMMIT TRAN

END

--SQL Script End