Home > Software design >  Save a Select/Except Union into a Temp Table
Save a Select/Except Union into a Temp Table

Time:10-28

This code does precisely what I want: finds the difference between two tables, including nulls, and returns them. Thanks to: sql query to return differences between two tables

(
    SELECT * FROM table1
    EXCEPT
    SELECT * FROM table2
)  
UNION ALL
(
    SELECT * FROM table2
    EXCEPT
    SELECT * FROM table1
) 

I am having trouble getting this to turn into a temporary table (or even a regular table) to store its results for later use. Is there a way that I can tack on INSERT INTO here or generate a temp table from this beautiful query?

CodePudding user response:

Select from your existing query as a sub-query INTO the temp table of your choice.

SELECT *
INTO #temp1
FROM (
    (
        SELECT * FROM @table1
        EXCEPT
        SELECT * FROM @table2
    )  
    UNION ALL
    (
        SELECT * FROM @table2
        EXCEPT
        SELECT * FROM @table1
    )
) X
  • Related