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
Pavan Kumar 722Pavan Kumar 722 

Dynamic SOQL using Custom Label

I am trying to place a SOQL statement inside a custom label which will be used in Dynamic Query. I need to reference few other custom labels  inside the SOQL but for some reason these custom labels are appearing as a string value. How do I reference a custom label within a custom label?  Ex: Select Id, Name from Product2 where Product_Ref_Key__c NOT IN(System.Label.ProductReferenceKey1, System.Label.ProductReferenceKey2)
Deepak Kumar 138Deepak Kumar 138
I think you need help with how to use the custom label which has another custom label name in dynamic query.
Let assume you have following custom labels - 
DynamicQueryString - 'Select Id, Name from Product2 where Product_Ref_Key__c NOT IN(System.Label.ProductReferenceKey1, System.Label.ProductReferenceKey2)'

ProductReferenceKey1 - 'product key 1'

ProductReferenceKey2 - 'product key 2'

This is how you can use it -
 
String prodRefKey1 = System.Label.ProductReferenceKey1;
String prodRefKey2 = System.Label.ProductReferenceKey2;

String queryString = System.Label.DynamicQueryString;
queryString  = queryString.replace('System.Label.ProductReferenceKey1',prodRefKey1 ); //replacing the label String with actual value in the label.
queryString  = queryString.replace('System.Label.ProductReferenceKey2',prodRefKey2 ); //replacing the label String with actual value in the label.

List<Product2 > prodList =  Database.query(queryString);

 
Pavan Kumar 722Pavan Kumar 722
Hi Deepak,

Thanks for your suggestion!  Thn problem with this solution is that, the very essence of making SOQL loosely coupled with Apex code is lost! If I  want to add any additional Custom Label inside SOQL statement I will then need to modify Apex code every time to replace the String!
Deepak Kumar 138Deepak Kumar 138

Yeah, thats right.

But wanted to understand why are you not using only one lable to have even the filters as well. if your are worried that a single label will not be able to store all the SOQL then. you can think on the having part of SOQL in each label and do like. query= System.Label.DynamicQueryString1+System.Label.DynamicQueryString2+System.Label.DynamicQueryString3; 

if that is also not going to work for your use case then think on using custom setting.