Activity › Forums › Salesforce® Discussions › Can we perform Dynamic SOQL for Cross-Objects?
Tagged: Cross Object, Database, Dynamic SOQL, List, Salesforce Query, SOQL
-
Can we perform Dynamic SOQL for Cross-Objects?
Posted by Piyush on April 30, 2016 at 6:29 PMCan we perform Dynamic SOQL for Cross-Objects
Matheus replied 9 years, 4 months ago 3 Members · 3 Replies -
3 Replies
-
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); - [adinserter block='9']
-
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 9 years, 4 months ago by
Matheus.
-
This reply was modified 9 years, 4 months ago by
-
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.