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
LaurenP6777LaurenP6777 

Conditional Queries in Apex Trigger

Hi guys, 

I just wrote a quick trigger that will link a child record (NSSO_Parent__c) to an Opportunity based on matching Protocol Number fields. This is working fine but there will be instances when multiple opportunities has the same Protocol Number. In this case, i would like to link the record to the Parent Opportunity - i would know the record is the parent opportunity IF the field "Parent_Opportunity__c" is blank. 

Basically I want a nice way of saying "Run this query and ONLY IF it returns multiple results, loop back thru and choose the one that has "Parent_Opportunity__c = null"

Here is my trigger. Any help would be greatly appreciated!!!!
trigger UpdateParentonNSSO on NSSO_Parent__c (before insert, before update){ 


    
  
    for(NSSO_Parent__c n : trigger.new)
    {

      if(n.Opportunity__c == null &&n.Protocol_Number__c!=null)
          {
     
           Opportunity SOpp = [SELECT Id from Opportunity where Protocol_Number__c = :n.protocol_number__c];
     
   
   
   
       
        n.Opportunity__c=SOpp.Id;
       
        }
 
 
}

}