[英]I need to insert the values from the second table to the first table whenewer the ID matches
I have 2 tables.我有 2 张桌子。 Below is the fields description.以下是字段说明。 1st table Fields: EmployeeID, Name, EmployeeStatus, PreferredName第一个表字段:EmployeeID、Name、EmployeeStatus、PreferredName
2nd table Fields: EmployeeID, PreferredName第二个表字段:EmployeeID,PreferredName
I need to insert the values of PreferredName from 2nd table to the first table whenever EmployeeID matches.每当 EmployeeID 匹配时,我需要将第二个表中的 PreferredName 值插入到第一个表中。 Currently all values of PreferredName in the 1st table are null.目前第一张表中所有 PreferredName 的值都是 null。 If no match by EmployeeID they should remain null.如果 EmployeeID 不匹配,则它们应保留为 null。 This is SQL Server.这是 SQL 服务器。
I am trying something like:我正在尝试类似的东西:
insert into [Table1] PreferredName values
SELECT
[PreferredName]
FROM [Table2]
where [EmployeeID] in (SELECT EmployeeID FROM [Table1]
I think you actually want to UPDATE
the table, not INSERT
new data.我认为您实际上想要UPDATE
表,而不是INSERT
新数据。 For that, you can use an UPDATE
with JOIN
query:为此,您可以使用UPDATE
和JOIN
查询:
UPDATE table1
SET table1.PreferredName = table2.PreferredName
FROM table1
JOIN table2 ON table2.EmployeeID = table1.EmployeeID
you can use not exists
keyword你可以使用not exists
关键字
insert into table1 (preferredname)
select t2.preferredname
from table2 t1 where
not exists (select 1 from table1 t1 where t1.preferredname = t2.preferredname)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.