Summary: 

Delete companies from database that doesn’t have any opportunities or leads assigned and persons that are not assigned to any company.


Resolution:

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.


update company
set Comp_Deleted = 1
WHERE Comp_CompanyId not IN
(
SELECT Comp_CompanyId
FROM Company, Opportunity, Lead
WHERE
(Comp_CompanyId = Oppo_PrimaryCompanyID and Oppo_Deleted is NULL) or
(Comp_CompanyId = Lead_PrimaryCompanyID and Lead_Deleted is NULL)
)

update Person
set Pers_Deleted = 1
WHERE Pers_CompanyId
IN
(select Comp_CompanyId from company where
Comp_Deleted = 1
)