Sql 从表1中选择特定列,并使用Where子句条件插入表2中的特定列

Sql 从表1中选择特定列,并使用Where子句条件插入表2中的特定列,sql,sql-server,sql-server-2008-r2,Sql,Sql Server,Sql Server 2008 R2,表1: |Id|Category_Id|Type_Id|Code| +--+-----------+-------+----+ |1 |1 |1 |A | |3 |2 |1 |B | |4 |1 |3 |C | |Id|Category_Id|Type_Id|Code_Id| +--+-----------+-------+-------+ |1 |1 |1 |N

表1

|Id|Category_Id|Type_Id|Code|
+--+-----------+-------+----+
|1 |1          |1      |A   |
|3 |2          |1      |B   |
|4 |1          |3      |C   |
|Id|Category_Id|Type_Id|Code_Id|
+--+-----------+-------+-------+    
|1 |1          |1      |NULL   |
|3 |2          |1      |NULL   |
|5 |9          |7      |NULL   |
表2

|Id|Category_Id|Type_Id|Code|
+--+-----------+-------+----+
|1 |1          |1      |A   |
|3 |2          |1      |B   |
|4 |1          |3      |C   |
|Id|Category_Id|Type_Id|Code_Id|
+--+-----------+-------+-------+    
|1 |1          |1      |NULL   |
|3 |2          |1      |NULL   |
|5 |9          |7      |NULL   |
如您所见,表2中的“Code_Id”列为空。我需要使用表1中“Id”列的值更新该列,条件是表1中“Category_Id”列和“Type_Id”列的值与表2中“Category_Id”列和“Type_Id”列的值匹配

我该怎么做?感谢您并期待您的帮助。

使用加入更新

update t2 set code_id=t1.id
from table2
join table1 t1 on t1.type_id=t2.type_id and t1.category_id=t2.category_id
使用连接

UPDATE t2
SET Code_Id = t1.Id
FROM Table2 t2
JOIN Table1 t1 on t2.Type_Id=t1.Type_Id and t2.Category_Id=t1.Category_Id

在所有情况下都必须使用别名,例如集合,因为在多个表中可能有相同的列名,而不会出现错误

UPDATE A 
set A.code_id = B.id
FROM table2 A
INNER JOIN table1 B on B.type_id=A.type_id and B.category_id=A.category_id

非常感谢。这很有效。我试图接受这个答案,但网站一直告诉我,我可以在5分钟内接受答案。无论如何,谢谢你的帮助