Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 当ID匹配时,我需要将第二个表中的值插入第一个表_Sql_Sql Server_Tsql - Fatal编程技术网

Sql 当ID匹配时,我需要将第二个表中的值插入第一个表

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

我有两张桌子。下面是字段描述。 第一个表字段:EmployeeID、名称、EmployeeStatus、PreferredName

第二个表字段:EmployeeID、PreferredName

每当EmployeeID匹配时,我需要将PreferredName的值从第二个表插入第一个表。当前,第一个表中PreferredName的所有值都为空。如果EmployeeID没有匹配项,则它们应保持为空。这是SQL Server

我正在尝试类似于:

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别担心,我很高兴能帮上忙。