Wild card search in soql

Use like operator along with % character in where clause of SOQL to implement wild card search. In the following example query returns account records matching input text with account name. %'input string'% in where clause returns all the accounts having the input string anywhere in the account name. For ex.if the input string is 'tech' , query will return account with names 'Willsinfotech' and also 'infotech solutions'

Visualforce
<apex:page controller="wildcardController">
  <apex:form >
    <apex:pageblock >
        <apex:inputtext value="{!inputtext}"/>
        <apex:commandbutton value=" Search " action="{!searchRecords}"/>
    </apex:pageblock>
    <apex:pageblock rendered="{!flagshow}">
      <apex:pageblocktable value="{!accList}" var="acc">
        <apex:column value="{!acc.name}"/>
        <apex:column value="{!acc.accountnumber}"/>
      </apex:pageblocktable>
    </apex:pageblock>
  </apex:form>
</apex:page>

Controller
Public class wildcardController {
    Public string inputtext{get;set;}
    Public List<account> accList{get;set;}
    Public boolean flagshow{get;set;}
    Public wildcardController(){
    flagshow = false;
    }    
    Public void searchRecords(){
    flagshow = true;
      accList = database.Query('select name,accountnumber from account where name like '+'\''+'%'+inputtext+'%'+'\'');
    }
}

4 comments:

  1. give me one example transient keyword

    ReplyDelete
  2. can u explain how i have to put single quets in a Query : 'select name,accountnumber from account where name like '+'\''+'%'+inputtext+'%'+'\''.

    ReplyDelete
    Replies
    1. single quote would be represented as /' i.e ' = /'

      Delete