Sql 当ID匹配时,我需要将第二个表中的值插入第一个表
我有两张桌子。下面是字段描述。 第一个表字段:EmployeeID、名称、EmployeeStatus、PreferredName 第二个表字段:EmployeeID、PreferredName 每当EmployeeID匹配时,我需要将PreferredName的值从第二个表插入第一个表。当前,第一个表中PreferredName的所有值都为空。如果EmployeeID没有匹配项,则它们应保持为空。这是SQL Server 我正在尝试类似于:Sql 当ID匹配时,我需要将第二个表中的值插入第一个表,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有两张桌子。下面是字段描述。 第一个表字段:EmployeeID、名称、EmployeeStatus、PreferredName 第二个表字段:EmployeeID、PreferredName 每当EmployeeID匹配时,我需要将PreferredName的值从第二个表插入第一个表。当前,第一个表中PreferredName的所有值都为空。如果EmployeeID没有匹配项,则它们应保持为空。这是SQL Server 我正在尝试类似于: insert into [Table1] Pref
insert into [Table1] PreferredName values
SELECT
[PreferredName]
FROM [Table2]
where [EmployeeID] in (SELECT EmployeeID FROM [Table1]
我认为您实际上想要
更新表,而不是插入新数据。为此,您可以将更新
与加入
查询一起使用:
UPDATE table1
SET table1.PreferredName = table2.PreferredName
FROM table1
JOIN table2 ON table2.EmployeeID = table1.EmployeeID
您可以使用不存在
关键字
insert into table1 (preferredname)
select t2.preferredname
from table2 t1 where
not exists (select 1 from table1 t1 where t1.preferredname = t2.preferredname)
认可的。感谢you@Michael别担心,我很高兴能帮上忙。