MS SQL 插入选择连接

2021-09-10 00:00:00 sql tsql sql-server

我有两张桌子

    TABLE1                        TABLE2
COLUMN1 COLUMN2               COLUMN1 COLUMN2
John      56                     56      A
Bob       45                     45      B 
Eva       68                     68      C

并且我需要将列添加到一个表中,事实上我将使用函数 join 从其他表中插入新列值

And I need add column to one table with fact I will insert into new column value from other table using function join

        TABLE1
COLUMN1 COLUMN2 COLUMN3
John      56      A
Bob       45      B 
Eva       68      C

ALTER TABLE [dbo].[Table1]
ADD Column3 nvarchar(255); 

INSERT INTO [dbo].[Table1] (column3)
SELECT table2.column2
from [dbo].[Table2] left join [dbo].[table1]
on table1.column2 = table2.column1

但是我得到了

        TABLE1
COLUMN1 COLUMN2 COLUMN3
John     56       A
Bob      45       B 
Eva      68       C
NULL     NULL     A
NULL     NULL     B
NULL     NULL     C

你能帮我修理我的插入物吗?

Can you help me to fix my insert?

推荐答案

真的需要更新表设置column3

Really you need to UPDATE the table setting column3

UPDATE t1 
SET column3 = t2.column2
FROM [dbo].[Table1] t1
JOIN [dbo].[table2] t2 ON t1.column2 = t2.column1

相关文章