1

I have a

 Map<String, String> objectNameWithQueryString;

objectNameWithQueryString consists of 'ObjectAPIName' as the key and a 'soql query string as the value'.

My requirement is to perform dynamic queries against each object and story all the results from all object in an SObject List.

However, it seems to me that the only way to so this is to use dynamic SOQL within for loop, which is not the best practise.

Is there any other way to perform this?

  • Depends upon your use case, if you wanna query all of them ... then it does not matter whther it's in for loop or 'n' time get operation ...may be you can explain your use case then you can get a better approach here. – Ayub Jan 28 at 10:32
3

SOQL queries are inherently single-object. You are correct that there is no way to implement this requirement as written without using iteration.

However, this requirement itself is rather suspect. If you have a need to perform the same query across multiple objects, you should at least evaluating using SOSL rather than SOQL.

If you simply need to perform multiple unrelated queries across distinct objects, it's not clear what you gain by centralizing that query activity in a single generic method using Dynamic SOQL. It is clear, however, what you lose by doing so:

  • Compile-time checking of fields and query syntax.
  • Static dependencies between your code and schema, ensuring that the Metadata API can check those relationships at deployment time.
  • The ability to use Apex binds in your queries.
  • The ability to use Selector-layer classes on a per-object basis.
  • You may have more difficulty tracking where you need to sanitize user input to avoid SOQL injection.
  • If you use any kind of static analyzer, it's going to complain about the SOQL in a loop.

I would push back strongly on adopting this implementation pattern.

| improve this answer | |
  • I need to to SOQLs because I need to search lookup fields values. Had they been normal text values, i would have most definitely used SOSL. As a result of this I am stuck – user55791 Jan 28 at 17:39

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.