Tuesday, March 21, 2017

Dynamic SOQL Query.

 public list<sObject> reclist = new list<sObject>();
 public string selectedObject = 'Account';
 public string SearchKey = 'test';
 string query =  'select id,Name from ' +selectedObject +' where Name LIKE \''+SearchKey+'%\' ORDER BY Name';
 reclist = database.query(Query);
system.debug('reclist =='+reclist );

Above Query will return the accounts whose name start with test.

 string query =  'select id,Name from ' +selectedObject +' where Name LIKE \'%'+SearchKey+'%\' ORDER BY Name';
 reclist = database.query(Query);

Above Query will return the accounts whose name Contains test.

string query =  'select id,Name from ' +selectedObject +' where Name=:SearchKey limit 1'; system.debug('query ==='+query );
sobject sobj = database.query(Query);

Above Query will return the account whose name exactly Equuleus to test(SearchKey).


string conName = 'test';
string conNameLike = '%' + String.escapeSingleQuotes(conName.trim()) + '%';
String query = 'SELECT Id, FirstName, LastName From Contact Where FirstName LIKE :conNameLike';
List<Contact> conList = Database.query(query);
System.debug('conList-' + conList);

Above Query will return the contacts whose FirstName contains test.

No comments:

Post a Comment