Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.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 Server:使用另一个表中的记录更新表_Sql_Sql Server 2012_Multiple Tables_Update Statement - Fatal编程技术网

SQL Server:使用另一个表中的记录更新表

SQL Server:使用另一个表中的记录更新表,sql,sql-server-2012,multiple-tables,update-statement,Sql,Sql Server 2012,Multiple Tables,Update Statement,我在SQL Server 2012数据库中有两个表employee和employee\u history。employee表包含所有员工的当前信息,employee\u history表跟踪每个员工的详细信息发生的所有更改 我的要求是用employee_history表中每个员工的最新记录更新employee表中的每个记录 例如: 员工表格: 员工历史记录表格: employee从employee\u历史记录更新后的表应为: 请注意:由于这只是一个示例,我只添加了最低限度的信息。但是,em

我在SQL Server 2012数据库中有两个表
employee
employee\u history
employee
表包含所有员工的当前信息,
employee\u history
表跟踪每个员工的详细信息发生的所有更改

我的要求是用
employee_history
表中每个员工的最新记录更新
employee
表中的每个记录

例如:

员工
表格:

员工历史记录
表格:

employee
employee\u历史记录更新后的表应为:

请注意:由于这只是一个示例,我只添加了最低限度的信息。但是,
employee
employee\u history
表都有许多其他列。每个表中都有一些列在另一个表中不存在。我不应该更新这些列

你能告诉我最简单的方法是什么吗

update a 
   set a.Emp_first_name = b.emp_first_name,
       a.emp_last_name  = b.emp_last_name, 
       a.Emp_Phone      = b.Emp_phone, 
       a.Emp_Address    = b.Emp_address, 
       a.Emp_dept       = b.Emp_dept
from employee as a
join  ( select * 
             , row_number over (partition by emp_id order by Updated_date  desc) as rn
        from employee_history  
      ) as b 
 on b.emp_id = a.emp 
and b.rn = 1


使用CTE正确连接表

;with hist as (
select *, row_number() over(partition by emp_id order by updated_date desc) rn
from employee_history
)
update employee
set Emp_First_Name = hist.Emp_First_Name --,more cols
from employee e
inner join hist on e.Emp_id = hist.emp_id and hist.rn = 1

使用CTE正确联接表

;with hist as (
select *, row_number() over(partition by emp_id order by updated_date desc) rn
from employee_history
)
update employee
set Emp_First_Name = hist.Emp_First_Name --,more cols
from employee e
inner join hist on e.Emp_id = hist.emp_id and hist.rn = 1

请用您正在使用的数据库标记您的问题。请用您正在使用的数据库标记您的问题。否。更新中的左侧始终属于要更新的表。否。更新中的左侧始终属于要更新的表。