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
AhmedPotAhmedPot 

Want to retrieve results from SOQL query without referencing column name as column name cn vary

My requirement is that I'm creating dynamic DML .Now I want to retrieve the result from the query but I don't know what the field names would be.

The question is, what do I do if I don't know the column names?

Imagine that I'm given a SOQL string to execute, and I don't know what the field names are.

I dont want to do Object.fieldname directly as Query may have different fieldname

 

for ex:

 

Contact c = [select name from Contact limit1];

 

can't call

c.get('name') or c.name

 

because I don't know what the name of the field is.

 

Any workaround wherein I can get the data without entering the column name?

 

Awaiting any replies.

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

The only way I can think of to do this is to use the describe functionality to retrieve a map of the fields for the object and then iterate through them.

 

Something like:

 

 

Contact c = [select name from Contact limit 1];

Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Contact.fields.getMap();

for (String key : fieldMap.keySet())
{
   Schema.SObjectField value=fieldMap.get(key);
   String fieldName=value.getDescribe.getName();
   String fieldValue=c.get(fieldName);
   System.debug('Field ' + name + ' value is ' + fieldValue);
}

 

 

 

All Answers

bob_buzzardbob_buzzard

The only way I can think of to do this is to use the describe functionality to retrieve a map of the fields for the object and then iterate through them.

 

Something like:

 

 

Contact c = [select name from Contact limit 1];

Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Contact.fields.getMap();

for (String key : fieldMap.keySet())
{
   Schema.SObjectField value=fieldMap.get(key);
   String fieldName=value.getDescribe.getName();
   String fieldValue=c.get(fieldName);
   System.debug('Field ' + name + ' value is ' + fieldValue);
}

 

 

 

This was selected as the best answer
AhmedPotAhmedPot

Ohh..gr8.

Thanks so much..I was able to get the things working...Thanks..