Delete companies from database that doesn’t have any opportunities or leads assigned and persons that are not assigned to any company.
Update Comp_Deleted = 1 field whenever Oppo_PrimaryCompanyID and Lead_PrimaryCompanyID will not be equal Comp_CompanyId, and after that update Pers_Deleted = 1 whenever they don't have company assigned.
set Comp_Deleted = 1
WHERE Comp_CompanyId not IN
FROM Company, Opportunity, Lead
(Comp_CompanyId = Oppo_PrimaryCompanyID and Oppo_Deleted is NULL) or
(Comp_CompanyId = Lead_PrimaryCompanyID and Lead_Deleted is NULL)
set Pers_Deleted = 1
(select Comp_CompanyId from company where
Comp_Deleted = 1