I am trying to accomplish the following:
SELECT col1, col2 FROM table1
UNION
SELECT col2, col3 FROM table2
With the result:
col1, col2, col3
1 , 1 , NULL
NULL, 1 , 1
The union of the columns and the rows is returned. You could think of it as the UNION equivalent of a FULL OUTER JOIN.
The simple answer to this question is:
SELECT col1, col2, NULL AS col3 FROM table1
UNION
SELECT NULL AS col1, col2, col3 FROM table2
This, however, is difficult to do with dynamic T-SQL and dbo.sp_executesql, and the resulting query could be too long if a large number of UNIONS is involved.
The best solution I could come up with was to create a temporary table with all the possible columns and insert each select into the temporary table in turn, like this:
CREATE TABLE #temp ( col1 int, col2 int, col3 int )
INSERT INTO #temp ( col1, col2 ) SELECT col1, col2 FROM table1
INSERT INTO #temp ( col2, col3 ) SELECT col2, col3 FROM table2
But this requires knowing ahead of time what the column names are. My particular scenario and this question assumes that if the column names match the types match as well. In fact, the columns that I am trying to manipulate are all of the same type.
Is there a simpler way to do this?
Thanks!