function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RoboRobo 

System.SObjectException: Invalid field

I do not understand why the following exception occurs:

System.SObjectException: Invalid field Opportunity.Account.Name for Opportunity

Here is the code:

        string dynamicSql = 'select Opportunity.Account.Name from Opportunity';
        for(sObject row: Database.query(dynamicSql)) {                   
            string analyzeType = String.valueOf(row.get('Opportunity.Account.Name'));
        }


Note: I am using the Database.Query because sql is generated on the fly which can be for other tables.

Best Answer chosen by Admin (Salesforce Developers) 
skodisanaskodisana
Hi,

Use the below code:

string dynamicSql = 'select Name,Account.Name from Opportunity';
for(Opportunity row: Database.query(dynamicSql)) {
string analyzeType = String.valueOf(row.Account.Name);
System.debug('analyzeType************ :'+analyzeType);
}

Thanks,
Srikanth. K

All Answers

Jake GmerekJake Gmerek

 string dynamicSql = 'select Account.Name from Opportunity';
        for(sObject row: Database.query(dynamicSql)) {                   
            string analyzeType = String.valueOf(row.get('Account.Name'));
        }

 

Try that and see if it works!

RoboRobo

No, still error:

 

System.SObjectException: Invalid field Account.Name for Opportunity

Jake GmerekJake Gmerek

Ok I dug a little deeper and here is what your rows contain (this is just one row)

 

15:56:07:033 USER_DEBUG [4]|DEBUG|Opportunity:{AccountId=001c0000008HrpSAAS, Id=006c00000037E57AAE}

 

As you can see there is no account.name.  What you may need to end up doing is gathering all the accountID's and then querying again on  the account object to grab the names.

skodisanaskodisana
Hi,

Use the below code:

string dynamicSql = 'select Name,Account.Name from Opportunity';
for(Opportunity row: Database.query(dynamicSql)) {
string analyzeType = String.valueOf(row.Account.Name);
System.debug('analyzeType************ :'+analyzeType);
}

Thanks,
Srikanth. K
This was selected as the best answer
Jake GmerekJake Gmerek

That will not work, the query is not returning account.name at all so whatever syntax that is used, you can not get account.name out of an object that does not contain it.  

skodisanaskodisana
Please execute the above code from Developer console.
it is working.
Jake GmerekJake Gmerek

OH! I see the difference, nevermind, good catch!  Yes it does.

RoboRobo

Thanks for the reply, the issue that I will have is the row.Account.Name is not in a string so I cannot change it on the fly depending on what I put in for the column.