Get more optimize query for Full Join or Cross Join
I need to return an portability combination output from 2 table. When table1 has rows but table2 is empty, it will still able to return the rows. I tried CROSS JOIN but failed. Seem like only FULL OUTER JOIN ON using join filter 1=1 can get the correct result. Any others better way?
declare @table1 table (col1 int, col2 int )
declare @table2 table (col1 int, col2 int )
insert into @table1 select 1, 11 union all select 2, 22
union all select 1, 22
-- When @table2 is empty, CROSS JOIN is return empty rows.
select t1.*, ISNULL(t2.col1, 0), ISNULL(t2.col2, 0)
from @table1 t1 CROSS JOIN @table2 t2
order by t1.col1, t1.col2, t2.col1, t2.col2
-- When @table2 is empty, still show record from @table1 with zero values
select t1.*, ISNULL(t2.col1, 0), ISNULL(t2.col2, 0)
from @table1 t1 FULL OUTER JOIN @table2 t2
on 1=1
order by t1.col1, t1.col2, t2.col1, t2.col2
Following result is currently what i want, but any possible it will wrong? or more better implementation?
-- When @table2 is empty, still show record from @table1 with zero values
select t1.*, ISNULL(t2.col1, 0), ISNULL(t2.col2, 0)
from @table1 t1 FULL OUTER JOIN @table2 t2
on 1=1
order by t1.col1, t1.col2, t2.col1, t2.col2