How to perform Soql query outside for loop?

Here is one approach.

  1. First get a set of the products you're going to need
  2. Get all the PBEntry records at once and put them on a map (key = the product name) so you can retrieve them easily later
  3. In your loop, check for the existence of records with that product name and, if they do, then retrieve the records and iterate to perform your logic

Sample Code

      //Create a Set with all the Products
      Set<String> productNames = new set<String>();
      for(Pricing__c prices: priceList) {
        productNames.add(prices.Name__c);
      }

     //Put the set in a map for easy access
     Map<String, List<PricebookEntry>> PBMap = new Map<String, PricebookEntry>();
     for (PricebookEntry  pb :  [SELECT Id, IsActive, CurrencyIsoCode FROM PricebookEntry
              WHERE  Product2.Name  in :productNames]) {

            if (! PBMap.containsKey(pb.Product2.Name)) {
               PBMap.put(pb.Product2.Name, new List<PricebookEntry>);
            }

            List<PricebookEntry> pbList =  PBMap.get(pb.Product2.Name);
            pbList.add(pb);
            PBMap.put(pb.Product2.Name, pbList);
     }

      for(Pricing__c prices: priceList) {

        If (PBMap.containsKey(prices.Name__c)){ 
           //Get all the PB Entries that matched  
           List<PricebookEntry> pbList =  PBMap.get(prices.Name__c);

            for(Pricebookentry PB: PBList){

                OpportunityLineItem OpItem=new OpportunityLineItem();
                oli.PriceBookEntryId=PB.Id;
                oli.Opportunityid=prices.Opportunity__r.id;
                oplineList.add(oli);
                }
        }

       insert oplineList;

Tags:

Soql

Apex

For