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.

  • 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. – pchittum Jan 9 '13 at 13:19
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){} }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.