2

following apex code

public String getLastUpdatedAt() {
String timeStr;
DatadoctorStatus__c last = [SELECT LastUpdated__c FROM DatadoctorStatus__c ORDER BY LastUpdated__c DESC LIMIT 1];
if (last == null){
    timeStr = 'Not yet updated.'; 
} else {
DateTime d = datetime.now();
    timeStr = d.format('MMMMM dd, yyyy hh:mm a z');
} 
return timeStr;
}

is giving me System.QueryException: List has no rows for assignment to SObject if there are no (zero) rows in DatadoctorStatus__c SObject.

1
  • By the way this is expected behavior. If you attempt to assign query results into a single sObject instance, the query must always return exactly one record or it throws an exception. Commented Jan 9, 2013 at 13:19

3 Answers 3

8

Change your query to:

List<DatadoctorStatus__c> last = [SELECT LastUpdated__c FROM DatadoctorStatus__c ORDER BY LastUpdated__c DESC LIMIT 1];
if (last.isEmpty()){
        timeStr = 'Not yet updated.'; 
} else {
        DateTime d = datetime.now();
        timeStr = d.format('MMMMM dd, yyyy hh:mm a z');
} 
1

Get the response in a list and then further do you manipulations.

List<DatadoctorStatus__c> last = [SELECT LastUpdated__c FROM DatadoctorStatus__c ORDER BY LastUpdated__c DESC LIMIT 1];
if (last.size() == 0){
        timeStr = 'Not yet updated.'; 
} else {
        DateTime d = datetime.now();
        timeStr = d.format('MMMMM dd, yyyy hh:mm a z');
} 

You can also use last.isEmpty() function instead of last.size() == 0. isEmpty() Returns true if the list has zero elements.

0

It works as expected.You can do 2 things 1) wrap the query in a try catch block

try{ query} catch(exception ex){}

2) make the last as a list than havng it as an instance of datadoctorstatus_c then do for(datadoctorstatus_c l: last) { if(l== null){} }

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.