2016-06-19 10 views
0

SQL Server 2012データベースに2つのテーブルemployeeemployee_historyがあります。 employeeテーブルには、すべての従業員の現在の情報が含まれ、employee_historyテーブルには、各従業員の詳細に発生したすべての変更が記録されます。SQL Server:別のテーブルのレコードを使用してテーブルを更新する

employeeテーブルの各レコードをemployee_historyテーブルの各従業員の最新レコードで更新する必要があります。

例えば:

employee表:

enter image description here

employee_history表:employee_historyテーブルから更新後

enter image description here

employeeテーブルは次のようになります

enter image description here

ご注意:を、これは一例に過ぎないとして、私は唯一の最小限の情報を追加しています。しかし、employeeemployee_historyの両方の表には、他の多くの列があります。各テーブルには、他のテーブルに存在しない列がいくつかあります。私はこれらの列を更新するはずがありません。

これを行う最も簡単な方法は何ですか?

+1

ご使用のデータベースに質問にタグを付けてください。 –

答えて

2

適切にテーブルを結合する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 
+1

更新の左側は常に更新対象のテーブルに属します。 –

0
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 

update

関連する問題