list has more than 1 row for assignment to sobject

You will get this kind of error whenever you try to put value in a variable(that can store a single value of defined type) and the right hand side query returns more than one values.For example, you have a variable of type account and you equate it with a select query that returns more than one record.
In the following example you will see the error "List has more than 1 rows for assignment" when you press the button.

Visualforce page
In this line,
 account acc = [select id from account ];
Variable acc can accept a single record but query returns more than one record which throws the exception "List has more than 1 rows for assignment"
Had there been a limit parameter specified with value 1 or if the query had returned exactly one record the exception wouldn't have appeared.
  account acc = [select id from account limit 1]; or
  account acc = [select id,name from account where id=:'somerecordID']
We can also get the field value in a variable from a query provided the query returns only one record as below:
String AccName = [Select name,id,accountNumber from account limit 1].name;
Make sure the fields whose value is to stored in variable should be queried as above.

No comments:

Post a comment