0

I have an object with number of records in this format with Name in Text format -

Id  Name
 1  A,B,C
 2  A,B
 3  A
 4  B
 5  A,C
 6  A,D

I have a multi-select picklist with values as:

A
B
C
D

So if I select B and C in my picklist, then I must have the records from the table in which name consists of B or C or (B and C) i.e. in this case, it should show 4 records:

1 A,B,C
2 A,B
4 B
5 A,C

I am using SQL query with IN and INCLUDES keyword but I am unable to achieve this functionality.

dimo414
  • 47,227
  • 18
  • 148
  • 244
Pranay
  • 1
  • 1
  • 1

1 Answers1

0

This depends on how many options you have for using soql. One way I can see it is:

Object__c myObject = new Object__c();
object.Name = 'A,B,D';
object.Multi_Select_Name__c = 'A;E';
insert object;
String query = 'select Id from Object__c';

//now we want to do a multi picklist, which is a String separated by ';'
List<String> nameSelections = object.Multi_Select_Name__c.split(';');
if(nameSelections.size() > 0) {
    query += ' where ';
    for(Integer i = 0; i < nameSelections.size(); i++) {
        nameSelections[i] = 'Name like \'%' + nameSelections[i] + '%\'';
    }
    query += String.join(nameSelections, ' or ');
}
List<Object__c> objects = (List<Object__c)database.query(query);

This will create a query like:

'select Id from Object__c where Name like '%A%' or Name like '%E%'

Selecting all Object__c's where Name contains either A or E, generated from your multiselect.

Syntax errors may apply, I just wrote this real quick :) Ill double check myself.

EDIT: This code works to build the query

String query = 'select Id from Object__c';
String multiSelect = 'A;E';
List<String> nameSelections = multiSelect.split(';');
if(nameSelections.size() > 0 ){
    query += ' where ';
    for(Integer i = 0; i < nameSelections.size(); i++) {
        nameSelections[i] = 'Name like \'%' + nameSelections[i] + '%\'';
    }
    query += String.join(nameSelections, ' or ');
}
system.debug(LoggingLevel.INFO, query);
Jared Kremer
  • 319
  • 1
  • 2
  • 8