Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
when i try to execute the below query am getting an error messahe "subquery returns more than 1 row " . How should i rewrite the query ?

SQL
Update table1 set facilityID =
(select facilityID FROM table2 as a inner join table3 as b
on a.name =b.PROV_ORG_NAME)

Thanks.
Posted
Updated 21-May-12 22:54pm
v2

Use SELECT TOP 1. I think it may be helpful.
SQL
Update table1 set facilityID =
(select TOP 1 facilityID FROM table2 as a inner join table3 as b
on a.name =b.PROV_ORG_NAME)
 
Share this answer
 
Comments
sravani.v 22-May-12 5:19am    
My 5!
VJ Reddy 22-May-12 6:20am    
Thank you, sravani :)
VJ Reddy's solution will get you rid of the error message. But the problem is different.
With your UPDATE query, you are about to update ALL rows of table1, with one value. I.e. all rows of table1 will have that facilityID value from table2 which was retrieved as the first value from the subquery. I am pretty sure that that is not intended, is it?
This means that you are missing a WHERE clause in the UPDATE query proper. Could you describe in plain English which further conditions must be applied to get the "correct" facilityID to the "correct" row in table1?
 
Share this answer
 
You can also try this code:

SQL
Update table1 set facilityID =
(select a.facilityID FROM table2 a, table3 b
WHERE a.name =b.PROV_ORG_NAME LIMIT 0,1)


Well, also your entire query needed to be rethink-ed. i can guess you might needed to make a function to solve the issue.
 
Share this answer
 
As Bernhard Hiller pointed out this will update all of your rows. If you're trying to fetch the correct facilityId for each row you should have a correlation in the sub query to the row that's being updated. For example something like (without knowing your actual need or table structure)
SQL
Update table1 set facilityID = (select facilityID 
                                FROM table2 
                                where table2.name = table1.prov_org_name)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900