Deleting one single company/legal entity in D365FO

We came across a customer requirement to delete one single company (legal entity) in their D365FO environment. This was due to a sell of that particular business and therefore the wanted (and had to) get rid of that data. This procedure is not supported in standard and also DSE-Team did not offer any helping hands.

This is what we did to achieve (PU33):

  1. Create a class extension of the class SysDatabaseTransDelete
    [ExtensionOf(classStr(SysDatabaseTransDelete))]
    final class SysDatabaseTransDelete_AXP_Extension
    {
       
    void deleteTable(SysDictTable sysDictTable)
        {
           
    Common  common;
            common = sysDictTable.makeRecord();

            select count(RecId) from common;

            if (common.RecId)
            {
                info(strFmt(
    ‘Deleting %1 records in %2’,
                             common.RecId,
                             sysDictTable.name()));
               
    //Exceptions (must be deleted with doDelete)
               
    if (sysDictTable.id() == tableNum(SalesLine))
                {
                    
    while select forupdate common
                    {
                        common.doDelete();
                    }
                }
            }

            next deleteTable(sysDictTable);
        }

        void handleNonTransTable(SysDictTable sysDictTable)
        {
           
    this.deleteTable(sysDictTable);

            next handleNonTransTable(sysDictTable);
        }
    }

  2. Additionally, delete following tables
    delete from BATCH where COMPANY = ‘xxx’
    delete from BATCHJOB where COMPANY = ‘xxx’
    delete from MAINACCOUNTLEGALENTITY where LEGALENTITY = ‘[CompanyInfo.RecId]’
  3. Run delete class on environment
    https://yourenvironment.sandbox.operations.dynamics.com/?cmp=lum&mi=SysClassRunner&cls=SysDatabaseTransDelete

That should be it. If you come across any table(s) we forgot, please let us know.

Ah, and please be extra careful when running this – as you can imagine, this could do quite a bit of harm…