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
SimrinSimrin 

Executing string as query in SOQL

Hello,

I have a usecase where,
I want to build the SQL query in string format.
and get the result in List.

Presently,
String skill = 'Skill1';
List<ProfileSkillUser> tempResult = [SELECT User.FirstName, User.LastName, ProfileSkill.Name, EFX_Skill_assessment__c FROM ProfileSkillUser WHERE ProfileSkill.Name like :skill];

In future,
String skill = 'Skill1';
String query = "SELECT User.FirstName, User.LastName, ProfileSkill.Name, EFX_Skill_assessment__c FROM ProfileSkillUser WHERE ProfileSkill.Name like :skill";
List<ProfileSkillUser> tempResult = Execute(query);

How can i achieve this ?


I tried to follow two things,
https://developer.salesforce.com/page/Secure_Coding_SQL_Injection
http://use-the-index-luke.com/sql/myth-directory/dynamic-sql-is-slow
query = "select * from users where user = '" +
      Request.form("user") + "' and password = '" +
      getSaltedHash(Request.form("password")) + "'";

queryResult = Database.executeQuery(query);

 
Best Answer chosen by Simrin
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Hi Simrin,

Try below query.
string processQuery = 'Select  User.FirstName, User.LastName, ProfileSkill.Name, EFX_Skill_assessment__c FROM ProfileSkillUser WHERE ProfileSkill.Name LIKE \'%' + skill+ '%\'';

DataBase.query(processQuery);

Let us know if it helps you.

All Answers

Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Hi Simrin,

Try below query.
string processQuery = 'Select  User.FirstName, User.LastName, ProfileSkill.Name, EFX_Skill_assessment__c FROM ProfileSkillUser WHERE ProfileSkill.Name LIKE \'%' + skill+ '%\'';

DataBase.query(processQuery);

Let us know if it helps you.
This was selected as the best answer
Darshan Shah2Darshan Shah2
Hi Simrin,

Just try below code and you will get result as expected.

String skill = 'Skill1';
String query = 'SELECT User.FirstName, User.LastName, ProfileSkill.Name, EFX_Skill_assessment__c FROM ProfileSkillUser WHERE ProfileSkill.Name like \''+skill+'\'';

List<ProfileSkillUser> tempResult = (List<ProfileSkillUser>)Database.query(query);

Kindly let me know whether its suffice your problem.

Warm Regards,
Darshan Shah