+ Start a Discussion
Anil IngleAnil Ingle 

How to find "Ultimate Parent" or "Top Level Account" in Account hierarchy?

Our organizations with work multi-level hierarchies of Account.
I was wondering if anyone knows how one can create a script Or SOQL to find out the "Ultimate Parent" and store the result in a field.

Thanks
Best Answer chosen by Anil Ingle
Lokeswara ReddyLokeswara Reddy
Hi Anil,

Try using this utility method which returns ultimate parent account for any given account id
 
public String GetTopLevleElement( String objId ){
        Boolean topLevelParent = false;
        while ( !topLevelParent ) {
            Account a = [ Select Id, ParentId From Account where Id =: objId limit 1 ];
            if ( a.ParentID != null ) {
                objId = a.ParentID;
            }
            else {
                topLevelParent = true;
            }
        }
        return objId ;
    }

Regards
Lokesh

All Answers

ManojjenaManojjena
Hi Anil,
How many level you may have ? Where you want this to implement in trigger or in class ? 

 
Lokeswara ReddyLokeswara Reddy
Hi Anil,

Try using this utility method which returns ultimate parent account for any given account id
 
public String GetTopLevleElement( String objId ){
        Boolean topLevelParent = false;
        while ( !topLevelParent ) {
            Account a = [ Select Id, ParentId From Account where Id =: objId limit 1 ];
            if ( a.ParentID != null ) {
                objId = a.ParentID;
            }
            else {
                topLevelParent = true;
            }
        }
        return objId ;
    }

Regards
Lokesh
This was selected as the best answer