Friday, March 30, 2012

help on updating a field in a table with the field content of another table

HI everybody need help on this..

I have two tables below

table1

country countryid

africa ___
usa ___
italy ___
Spain ___

table2

countryid country name

1 africa
2 germany
3 italy
4 usa

I need to write the countryid of table 2 to the field countryid in table1 using the criteria of the correspoinding country name table 2 to country of table 1 if it write countryid else 0..

THE RESULT WOULD BE

country countryid

africa 1
usa 4
italy 3
spain 0

thanksShow us what you've come up with so far.|||yes trying this sql and it executed well and updated the first table

UPDATE table1
SET countryid=(SELECT countryid FROM table2
WHERE cntryname=country)

thanks anyway|||the solution worked fine until it didn't encounter a duplicate value... since it is a 1 to many relationship it gave me this error...

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

thanks again|||you mean you have two different countries with the same name? which ones? my geography skills aren't as good as I thought... :)|||use JOIN, something like -

UPDATE table1
SET countryid= COALESCE(table2.countryid, 0)
from table1
left outer Joint table2
ON
table2.cntryname=table1.country|||alexyeth,
I think the problem is that "africa" is not a country but continent.
:)|||thanks everybody.. the solution of mihir is great using the coalesce function...

No comments:

Post a Comment