I have an SObject say Account which has some not null fields. I want to select all the accounts matching those values. Is there a way I can create a dynamic SOQL query for this.
Suppose the Account object is like this:
Account anAccount = new Account();
anAccount.Name = "sample"
anAccount.CustomName__c = "custom sample"
//Match all account matching above criteria
List<Account> matchingAccounts = [SELECT id from Account where Name=:'sample' AND CustomName__c=:'custom sample'];
I want to make above query dynamically using anAccount instance.
Attribution to: vishesh
Possible Suggestion/Solution #1
Sure! You can use DML database methods but you have to escape the single quotes. There is a bunch of code on this page for creating a dynamic search app.
You would use something like the following:
List<Account> matchingAccounts = Database.query('SELECT id from Account where Name = \''+String.escapeSingleQuotes(your-account-name-var)+'\'' AND CustomName__c = \''+String.escapeSingleQuotes(your-customer-name-var)+'\''');
Attribution to: Jeff Douglas
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/33276