0

I have two tables that contain the same unique key. I need to match those keys and then copy data from table 2 into table 1

Original:

Key COL1 COL2          Key COL3
 1   01  NULL           1   05
 2   02  NULL           2   12
 3   03  NULL           3   27

Required:

Key COL1 COL2          Key COL3
 1   01   05            1   05
 2   02   12            2   12
 3   03   27            3   27

Thank you for the help.

Polarbehr
  • 15
  • 3

2 Answers2

0

Your best answer is probably an UPDATE FROM a lookup based on the two tables (for SQL Server, some say use JOIN, some say there's no need, and without the join is more concise).

See some examples here: SQL update from one Table to another based on a ID match

For convenience, here's a query adapted for your scenario:

UPDATE Table1 SET 
    Col1 = Table2.Col1,
    Col2 = Table2.Col2,
    Col3 = Table2.Col3,
FROM Table2
WHERE Table2.Key = Table1.Key
Community
  • 1
  • 1
SlimsGhost
  • 2,849
  • 1
  • 10
  • 16
0

TRY this:

update table1 set col2 = ( select col3 from table2 where table2.key=table1.key ) where exists ( select * from table2 where table2.key=table1.key );

  • Can you explain your answer instead of just dumping code in here? That way people can learn from it. – Robert Oct 19 '16 at 21:58
  • Use update statement by setting the value in table2 from table1 by filtering using keys from both tables. Or you can use join also to get the same result. – viswanath n Oct 19 '16 at 22:04