+ Start a Discussion
ngabraningabrani 

SOQL query where the object name and field names are dynamic

I need to perform a SOQL query in Apex with dynamic parameters. The object names and field names are dynamic. A query something like
select :fieldName1, :fieldName2 from :objectName

The fieldName1, fieldName2 and objectName will be known only at runtime.

Is there any way to perform such a query in Salesforce?

Many Thanks,

Naveen

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

Sounds like you need to use dynamic SOQL.

 

In this case you construct the query string at runtime and then execute it using the Database.query method.

 

E.g.  

 

String queryStr='select '+ fieldName1 + ', ' + fieldName2 + 'from ' + objectName;

List<Sobject> results=Database.query(queryStr);

There's more information at:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm

 

 

The SOQL injection section is worth reading if you are planning to include user input in your query string.

All Answers

bob_buzzardbob_buzzard

Sounds like you need to use dynamic SOQL.

 

In this case you construct the query string at runtime and then execute it using the Database.query method.

 

E.g.  

 

String queryStr='select '+ fieldName1 + ', ' + fieldName2 + 'from ' + objectName;

List<Sobject> results=Database.query(queryStr);

There's more information at:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm

 

 

The SOQL injection section is worth reading if you are planning to include user input in your query string.

This was selected as the best answer
Mohamed Azarudeen 21Mohamed Azarudeen 21
Bob, Please help me for below logics

Orginal Query

Select name,Salary from Account where (name ='Smith' and Salary > 10000)

My Visulaforce page

No   Fields   Clause        Value

1)   name     equals             Smith
2)   Salary   Greater than    10000  
 

Dynamic Query looks like

Select name, Salary from Account where (Fields Clause Value)

Can you please help me for this Apex class logic?