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
V AnandV Anand 

System.QueryException: List has no rows for assignment to SObject

Trigger AttachTrig on Attachment (after delete, after insert, after update) {
 
 folder f=[select id,name,type from folder where name='xxx' and type='document' limit 1];
 list<document> docc=[select name,body,description,folderid,bodylength from document where folderid=:f.id ];
 list<contact> con=[select id from contact where recordtypeid=:[select id from recordtype where name='abc']]; 
  
  
  if(trigger.isInsert){
     document doc= new document();
      attachment attach=[select name,description,body,parentid from     attachment where id=:trigger.new and parentid in :con];
contact c=[select id,Cn__c from contact where id=:attach.parentid];
        doc.name=attach.name;     
        doc.body=attach.body;
        doc.folderid=f.id;
        doc.keywords=c.Cn__c;
        insert doc;
       
  }

}

 some times its works perfectly....some times above code cause an error  like System.QueryException: List has no rows for assignment to SObject

 

please help me for better coding.....

 

bob_buzzardbob_buzzard

Which line(s) do you see the error being thrown from?

Rahul SharmaRahul Sharma

vel123, Assigning a query to a Object is not a good practice. Always assign query to list and use 0th value from that list if the query retrieves any value.

 

Example:

 

Account a = [Select Id from account where Name = 'Test' limit 1];  
//Not a good practise and will thow same exception when you dont'a have any Account with Name test
List<Account> lstAccount = [Select Id from account where Name = 'Test' limit 1];
Account a = new Account();
if( !lstAccount.isEmpty() ){
    a = lstAccount[0];
}
//This will not throw the exception

 

V AnandV Anand

This line cause an error...

 

 attachment attach=[select name,description,body,parentid from     attachment where id=:trigger.new and parentid in :con];
SammyComesHereSammyComesHere

This would help

 

Always do assignment to a list if you are not 100% sure that System would return you that record.

 

http://forums.sforce.com/t5/Apex-Code-Development/APEX-List-has-no-rows-for-assignement-to-SObject-problem/m-p/66796