Activity Forums Salesforce® Discussions Can we perform Dynamic SOQL for Cross-Objects?

  • Gourav

    Member
    May 24, 2016 at 10:48 am

    Hi Piyush,

    I don't know your exact need but Yes, we can perform Dynamic SOQL for Cross-Objects. Look below for example:-

    String str = 'date%';
    String query = 'Select id,name,(Select id,name from Contacts) From Account where name like :str';
    List<sObject> sobjList = database.query(query);
    system.debug('sobjList::'+sobjList);

  • Matheus

    Member
    January 31, 2017 at 10:10 pm

    I am wondering if there is an easy way to dynamically query accounts based on the account having the primary FSE name attached to it. The Primary_FSE__c field is on the Installed Product Object, which is a related list to the account page. The thing I can't figure out is how to insert each FSE's name dynamically into the SOQL query at the bottom of this apex class. So where it states \'Tim Bowen%\', I need that to be where the query places the correct FSE on there (which is what the where id =:ApexPages.currentPage().getParameters().get('id) is referencing).

    Dynamic SOQL allows simple bind variables to be hooked into the query. So providing you create a simple variable - fseLike in the code below - you can just use the normal bind syntax:

    @RemoteAction
    public static List<Account> getNearbyTech(Decimal latitude, Decimal longitude) {
    String fseLike = sgm.name + '%';
    String q = '...';
     ....
     q += 'AND id in (select SVMXC__Company__c from SVMXC__Installed_Product__c '
     q += 'where (Primary_FSE__c like :fseLike) AND ...';
    return Database.query(q); 
    }
    
    PS: Any values used in a remote action have to be passed from the client-side so you'll need to add the parameter and change the client-side to match (i.e. add '{!sgm.name}'to the JavaScript function parameter list):@RemoteAction
    
    public static List<Account> getNearbyTech(String fse, Decimal latitude, Decimal longitude) {
    
     String fseLike = fse + '%';
    
     String q = '...';
     ....
     q += 'AND id in (select SVMXC__Company__c from SVMXC__Installed_Product__c '
     q += 'where (Primary_FSE__c like :fseLike) AND ...';
    
     return Database.query(q); 
    }

    StackExchange is your friend.

    • This reply was modified 7 years, 9 months ago by  Matheus.
  • Matheus

    Member
    January 31, 2017 at 10:18 pm

    PS: When using dynamic queries, please sanitize your variables in order to avoid any sort of SQL injection.

    Please use this guide: SOQL Injection Vulnerability in Apex 

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos