Erechtheus
Erechtheus

Reputation: 765

Combine two tables into one table with separated values

This is a simple rather simple question, but for whatever reason I just can't get to a solution.

How do I join the two tables like such that I have get NULL values like this?

Table #T1

A
--
1
2

Table #T2

B
--
3

Desired result:

A  B
----
1 NULL
2 NULL
NULL 3

EDIT:

My solution was this

SELECT #T1.A, #T2.B 
FROM #t2 
RIGHT JOIN #T1 ON 1 = 0

UNION

SELECT #T1.A, #T2.B  
FROM #t2 
LEFT JOIN #t1 ON 1 = 0

But it seems overly complicated. Anything better?

Upvotes: 0

Views: 62

Answers (2)

Dileep Cherukuri
Dileep Cherukuri

Reputation: 21

This is the better/simple one

SELECT #T1.A, #T2.B 
FROM #t2 
FULL OUTER JOIN #T1 ON 1 = 0

Upvotes: 0

Pரதீப்
Pரதீப்

Reputation: 93754

Use FULL JOIN

select * 
   from #t1 t1
   full outer join #t2 t2 on t1.a = t2.b

or use UNION ALL

select a,Null as b 
from #t1
union all 
select NULL, b 
from #t2

since there is no common records in both the tables, both the query results will look same. When there is a common record, the result will differ. Use the one that suits your requirement

Upvotes: 3

Related Questions