[SalesForce] How to you query all objects for fields with the same name

For example, search all objects to find those that have a field named "Phone__c", and then query those fields.

The intent is to then update the "Phone__c" field on all the records that exist in those objects.

Thanks!

Best Answer

You can iterate each object and its fields to find those which have a specific API Name as below. I recommend you perform any queries separately, one per transaction.

public static List<SObjectType> getObjectsWithField(String apiName)
{
    List<SObjectType> sObjectTypes = new List<SObjectType>();
    for (SObjectType sObjectType : Schema.getGlobalDescribe().values())
    {
        if (sObjectType.getDescribe().fields.getMap().containsKey(apiName))
        {
            sObjectTypes.add(sObjectType);
        }
    }
    return sObjectTypes;
}