Tarkus
Tarkus

Reputation: 234

T-SQL for merging data from one table to another

Let's say there are 2 tables Table1 { ID, Name, Other } and Table2 { ID, Name, Other }. Both of them have identical records with the same IDs except that in Table1 all Name values are NULL. How can I import Name values from Table2 to Table1 using T-SQL (SQL Server 2008)?

Upvotes: 1

Views: 3835

Answers (4)

Guffa
Guffa

Reputation: 700232

Just join the tables and update:

update t1
set [Name] = t2.Name
from Table1 t1
inner join Table2 t2 on t2.ID = t1.ID

Upvotes: 0

Update Table1
Set Table1.Name = Table2.Name
From
Table1 INNER JOIN Table2 on Table1.ID = Table2.ID

Upvotes: 5

Jhonny D. Cano -Leftware-
Jhonny D. Cano -Leftware-

Reputation: 18013

UPDATE Table1
SET Table1.Name = Table2.Name
FROM Table2
WHERE Table1.Id = Table2.Id
--AND Table1.Name IS NULL

Upvotes: 0

Dillie-O
Dillie-O

Reputation: 29725

You're looking for the MERGE command, which is like the UPSERT that you've probably read about elsewhere. Here's a quick article about it.

Upvotes: 1

Related Questions