简体   繁体   English

T-SQL用于将数据从一个表合并到另一个表

[英]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 }. 假设有2个表Table1 {ID,Name,Other}和Table2 {ID,Name,Other}。 Both of them have identical records with the same IDs except that in Table1 all Name values are NULL. 它们都具有相同的记录,并且具有相同的ID,只是在表1中所有“名称”值均为NULL。 How can I import Name values from Table2 to Table1 using T-SQL (SQL Server 2008)? 如何使用T-SQL(SQL Server 2008)将Name值从Table2导入Table1?

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

You're looking for the MERGE command, which is like the UPSERT that you've probably read about elsewhere. 您正在寻找MERGE命令,就像您可能已在其他地方阅读过的UPSERT一样。 Here's a quick article about it. 这是一篇简短的文章

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

Just join the tables and update: 只需加入表并更新:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM