PJW
PJW

Reputation: 5397

Combining Values from SQL Table into a Second Table

I have one master table in SQL Server 2012 with many fields.

I have been given an excel spreadhseet with new data to incorporate, so I have in the first instance, imported this into a new table in the SQL database.

The new table has only two columns 'ID', and 'Source'.

The ID in the new table matches the 'ID' from the master table, which also has a field called 'Source'

What I need to do is UPDATE the values for 'Source' in the Master table with the corresponding values in the new table, ensuring to match IDs between the two tables.

Now to Query and see all the information together I can use the following -

SELECT m.ID, n.Source
FROM MainTable AS m
INNER JOIN NewTable AS n ON m.ID = n.ID

But what I don't know is how to turn this into an UPDATE statement so that the values for 'Source' from the new table are inserted into the corresponding column in the master table.

Upvotes: 0

Views: 31

Answers (3)

user2989408
user2989408

Reputation: 3137

You could do

UPDATE MainTable
    SET MainTable.Source = NewTable.Source
FROM NewTable
WHERE MainTable.ID = NewTable .ID

Upvotes: 1

Rich
Rich

Reputation: 865

first alter your main table, then:

update a
SET a.Source = b.Source
FROM MainTable a
JOIN NewTable b
 on a.ID = b.ID

Upvotes: 0

jzworkman
jzworkman

Reputation: 2703

UPDATE 
   MainTable
SET 
   MainTable.Source = NewTable.Source
FROM
   MainTable
INNER JOIN 
   NewTable
ON 
   MainTable.ID = NewTable .ID

That should do the trick

Upvotes: 1

Related Questions