Skip to content
Advertisement

Merge two tables in SQL, with one common column

I’m trying to merge to tables in MSSQL, as in the sample below. My situation is similiar to this question. T-SQL merging two tables with common and uncommon columns

I have tried using the following query:

But it results in this, where the rows that have the same value in column a, merges in the same row

Table1_test:

Table2_test:

Merged Table I want:

Advertisement

Answer

You can use the following using UNION ALL:

You can also use the FULL OUTER JOIN with a false match condition (1 = 2):

You can also generate the above SQL query (in case there are a lot of columns, or you don’t want to pick the common / uncommon column names yourself):

You can put the above script into a stored procedure with two parameters to make the script more flexible. You can find an example of the stored procedure on the demo.

demo on dbfiddle.uk

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement