I have table A and table B . I have to compare this tables records and insert data to table C using SQL Server procedure in below format
table A
name
A
B
C
D
E
F
G
table B
name
A
B
Q
C
D
F
G
table c should be like below. it has an extra field 'status' to mention record is added or removed.
name status
A
B
Q newly added
C
D
E removed
F
G
I know we can compare 2 tables and find added or removed records using EXCEPT and UNION operations. But in this case, I have to integrate that records with unchanged records and should place that added or removed records in correct position.
You could try using a some union and left join
Depending on which order do you want to accomplish at the end you can use this:
And then if you want to order by how it is in table a then in first select select
from b left join a
and in your second selectfrom a left join b
and if you want to oder by how it is in table b then in first select selectfrom a left join b
and in your second selectfrom b left join a
.Here is a demo with the last requested samle data.
You should use FULL OUTER JOIN.
There ise one more possible method:
please try with below query (SQL FIDDLE):
You can do this with a
full join
and conditional logic:Demo on DB Fiddle: