'Update Record and Insert Data from One Table Via Join
I have a table (Table 1) which is a list of employees and data points about them. The data that populated Table 1 is regularly changed and added to in its source system and then is loaded into another table (Table 2) via a CSV.
If data changes for a certain employee, I want to update that employees record in Table 1 and then append that changed employee to Table 1 along with any new employees from Table 2 that didn't already exist in Table 1.
Example:
Table1:
Status | ID | Name | Department | Title
Active 767 John Tech Analyst
Active 789 Alex Tech Courier
Table2:
Status | ID | Name | Department | Title
Active 767 John Tech Director -- the title changed for this employee
Active 789 Alex Tech Courier
Desired Output of Table1:
Status | ID | Name | Department | Title
Active 767 John Tech Director
Changed 767 John Tech Analyst
Active 789 Alex Tech Courier
With the query below, I am attempting to insert this data via an outer join however I am producing duplicates of each row, when I only want to add employees who have changed their department, title, etc. and any new employees that don't already exist in Table1
How can I insert this data without duplicating all the roles.
Query:
UPDATE [DATABASE].[dbo].[CBC_legacy]
SET [Position Status] = 'Changed'
FROM [DATABASE].[dbo].[CBC_data] CBC
WHERE (CBC.[Employee ID] = [CBC_legacy].[employee ID] AND (CBC.[Job Title] <> [CBC_legacy].[Job Title] OR CBC.[Home Department] <> [CBC_legacy].[Home Department] OR CBC.[Annual Salary] <> [CBC_legacy].[Annual Salary]))
INSERT INTO [DATABASE].[dbo].[CBC_legacy] (
[Position Status]
,[Employee ID]
,[Full Legal Name]
,[Annual Salary]
,[Job Title]
,[Home Department]
SELECT
[CBC].[Position Status]
,[CBC].[Employee ID]
,[CBC].[Full Legal Name]
,[CBC].[Annual Salary]
,[CBC].[Job Title]
,[CBC].[Home Department]
FROM [DATABASE].[dbo].[CBC_data] AS CBC
FULL JOIN [DATABASE].[dbo].[CBC_legacy] AS CBCL
ON [CBC].[Employee ID] = [CBCL].[Employee ID]
AND [CBC].[Job Title] = [CBCL].[Job Title]
AND [CBC].[Home Department] = [CBCL].[Home Department]
AND [CBC].[Annual Salary] = [CBCL].[Annual Salary]
ORDER BY [Full Legal Name]
SELECT * FROM [DATABASE].[dbo].[CBC_legacy] ORDER BY [Full Legal Name]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
