Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Join problem? 3

Status
Not open for further replies.

dukeslater

Technical User
Joined
Jan 16, 2001
Messages
87
Location
US
This is a simple update, but delivering unexpected results. I need to update only the records in table1 that exist in table 2:


update table1 a

set a.code =
( select code
from table2 b
where a.custid = b.custid);

This does properly update the records that exist in both tables.

Yet for those records that do not exist in table2 the statement is replacing the code in table1 with null. Ordinarily this would suggest a join problem, but I can't see why the equal join wouldn't do what I need.

Perhaps I need to use an entirely different technique, but I'm still stumped as to why I'm getting the result that I am. Thanks in advance for your help.
 
You have no WHERE clause on table1, so it will attempt to update every row even when there is no matching row in table2.

You could try

Code:
update table1 a
set a.code =
( select code
  from   table2 b
  where  a.custid = b.custid)
WHERE EXISTS (SELECT 1
              FROM   table2 c
              WHERE  c.custid = a.custid);
 
Perfect, thanks. Seems like I tried that, but obviously I had it wrong...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top