0

I have the following code sample:

@AuraEnabled
public static string getDunsByRecordId(id currentRecordID) {
    String q = 'SELECT DunsNumber FROM Account  where Id=:currentRecordID limit 1';
    List<String> dunsNumbers= Database.query(q);
    return dunsNumbers[0];
}

I want to receive the DUNS number of the record that I'm currently on, and retrieve it to the component.

The thing is, from what I understand, a query always return a list as a result, not a string.

When I write the line List<String> dunsNumbers= Database.query(q);, there is an error:

Illegal assignment from List to List

  1. How do i make it work? How do I receive one string as a duns number?
  2. Is there a way to receive a string, and not a list, as a result of a query?
1
  • You will receive List<Account> from your query and then you can loop on it to get your DunsNumber field.
    – SF_user
    Commented Mar 28, 2017 at 9:20

3 Answers 3

2

Your query returns list of accounts. You cannot assign it to a list of String. Whenever you need field value from any object you need SOQL. Try the below code.

@AuraEnabled
public static string getDunsByRecordId(id currentRecordID) {
    List<Account> accounts = [SELECT Id, DunsNumber 
                              FROM Account  
                              WHERE Id = :currentRecordID 
                              LIMIT 1];
    return (!accounts.isEmpty()) ? accounts[0].DunsNumber : '';
}
2
  • what do u mean by custom field?
    – Dana Griff
    Commented Mar 28, 2017 at 9:38
  • DunsNumber is a standard field in account so need to append __c.
    – Reshma
    Commented Mar 28, 2017 at 9:43
2

You can try this,

public static string getDunsByRecordId(id currentRecordID) {
    String q = 'SELECT DunsNumber FROM Account  where Id=:currentRecordID limit 1';
    List<Account> dunsNumbers= Database.query(q);
    String dunsNumber = '';
    if(dunsNumbers.size() != 0)
       dunsNumber = dunsNumbers[0].DunsNumber;
    return dunsNumber;
}

As you are querying only one account so no need to looping over it.

0

Refer to this Using SOQL Queries That Return One Record in Apex Developer Guide. You can get the single values from SOQL as below.

String name = [SELECT Name FROM Account WHERE Id=:currentRecordID limit 1].Name;
Double AnnualRevenue = [SELECT AnnualRevenue FROM Account WHERE Id=:currentRecordID limit 1].AnnualRevenue;

System.debug('name'+name);
System.debug('AnnualRevenue'+AnnualRevenue);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .