0
String objkey='Opportunity';
string recordID = '0061k000007Pyuf';
string soqlQueryCurrent='Id, Name, currency_Culture__c';
string queryStr ='SELECT '+soqlQueryCurrent+' FROM '+objkey+ ' WHERE id=:recordID WITH SECURITY_ENFORCED'; 
sObject sObjRecords = Database.query(string.escapeSingleQuotes(queryStr));
system.debug('sObjRecords: '+sObjRecords);

error:-System.QueryException: No such column 'currency_Culture__c' on entity 'Opportunity'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.

I want to ignore or bypass currency_Culture__c.

1

You need to specifically construct the query to omit the field when not available. For example:

String objkey='Opportunity';
string recordID = '0061k000007Pyuf';

// Using an array for the fields to get is clean
String[] fields = new String[]{'Id', 'Name'};

// This is an efficient way to get the describe for the SObject
SObject obj = (SObject) Type.forName(objkey).newInstance();
DescribeSObjectResult describe = obj.getSObjectType().getDescribe();

// See if the field exists and add it to the fields to query if it does
if (describe.fields.getMap().containsKey('currency_Culture__c')) {
    fields.add('currency_Culture__c');
}

// Use String.join to handle turning the array into the comma separated list of fields
string queryStr ='SELECT '+ String.join(fields, ', ') +' FROM '+objkey+ ' WHERE id=:recordID WITH SECURITY_ENFORCED'; 

sObject sObjRecords = Database.query(string.escapeSingleQuotes(queryStr));
system.debug('sObjRecords: '+sObjRecords);
0

In Case you don't want to check explicitly all the fields, You can follow below approach to iterate through all the fields to check weather they are valid and construct the valid soql query.

String objkey='Opportunity';
string soqlQueryCurrent='Id, Name, currency_Culture__c';

List<String> validsFieldList = new List<String>();

//get the describe for the SObject
SObject so = Schema.getGlobalDescribe().get(objkey).newSObject();

//run for loop on list of fields by splitting the query string
for(String fieldName : soqlQueryCurrent.split(', ')){
    //check if field is valid
    if(so.getSobjectType().getDescribe().fields.getMap().containsKey(fieldName)){
        validsFieldList.add(fieldName);
    }
}

//create the valid query string
soqlQueryCurrent = String.join( validsFieldList, ',' );
system.debug(soqlQueryCurrent);

enter image description here

1
  • Don't use global describe - it is much faster to use the approach I used. Performance can be important, depending on what you are doing.
    – Phil W
    Oct 14 '20 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.