2

I have gone through a situation where I want to query over an object which is selected by user. User can select an object out of a 10-15 objects. The way I know is to check each object and then query directly from database. Is it possible to write a single dynamic query and assign to sobject so that I can reduce the number of code.?

9

Yes, you can achieve this with the use of Dynamic SOQL. The syntax is this...

List<sObject> L = Database.query(string);

As per the docs...

The database query method can be used wherever an inline SOQL query can be used, such as in regular assignment statements and for loops. The results are processed in much the same way as static SOQL queries are processed.

In your case so long as you have a common set of fields or at least able to discover other fields per object (via Apex Describe) you could do something like this...

String myObject = 'Test__c';
String myLikeString = '%Test%';
List<sObject> records = Database.query('Select Id, Name From ' + myObject + ' Where Name Like :myLikeString');
for(SObject record : records)
     System.debug((String) record.get('Name'));

You will also need to study Dynamic Apex further to access the information generically, using the SObject methods. Keep in mind when using this approach the security consideration known as SOQL Injection...

SOQL Injection: SOQL injection is a technique by which a user causes your application to execute database methods you did not intend by passing SOQL statements into your code. This can occur in Apex code whenever your application relies on end user input to construct a dynamic SOQL statement and you do not handle the input properly.

See the documentation here for a full summary.

  • Your very welcome, i love the dynamic aspects of Apex! :-) – Andrew Fawcett Jan 23 '14 at 11:01
  • Had a clue it should be there so I pointed this. Anyway thanks again – Shebin Mathew Jan 23 '14 at 11:02

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.