Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move UNION query results to a new table?

Tags:

I have a sample query as shown below:

SELECT     * FROM         [#temp1] UNION SELECT     * FROM         [#temp2] UNION SELECT     * FROM         [#temp3] UNION SELECT     * FROM         [#temp4] UNION SELECT     * FROM         [#temp5] 

How do I move this request of these queries into a new table? Note: My verison of SQL is:

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)   Mar 29 2009 10:11:52   Copyright (c) 1988-2008 Microsoft Corporation  Enterprise Edition (64-bit) on Windows NT 6.0 <X64> (Build 6002: Service Pack 2)  

I tried another Stackoverflow answer I found, i.e.

CREATE TABLE managers AS SELECT * FROM employees WHERE desg = 'MANAGER'; 

But I get an error of : Incorrect syntax near the keyword 'as'.

Here was my full query that failed with the above error:

CREATE TABLE #temp_UNION as   SELECT     * FROM         [#temp1] UNION SELECT     * FROM         [#temp2] UNION SELECT     * FROM         [#temp3] UNION SELECT     * FROM         [#temp4] UNION SELECT     * FROM         [#temp5] 

Any suggestions please on how I'm goofing up?

Thank you, Ray

like image 472
Ray Avatar asked Jun 23 '11 15:06

Ray


People also ask

How do you create a new table from UNION of two tables in SQL?

If you want to make the new table with the same schema as the existing one, then one way might be to read the definition from the schema table, substitute a new table name, and then execute that SQL statement. That cannot be done purely in SQL, but it can be done in a C program.

Can we UNION more than two tables?

Combining several tables to one large table is possible in all 3 ways. As we have seen, the behavior of UNION in SQL Server and UNION in DAX within Power BI is very similar. Here tables with the same number of columns are placed directly under each other.


2 Answers

In SQL Server you have to use

SELECT <COLUMNS_LIST>   INTO <NEW_TABLE_NAME>   FROM <TABLES, WHERE ETC> 

More information @ http://msdn.microsoft.com/en-us/library/ms188029.aspx

Try this:

SELECT *   INTO  #temp_UNION  FROM (         SELECT     *     FROM         [#temp1]     UNION     SELECT     *     FROM         [#temp2]     UNION     SELECT     *     FROM         [#temp3]     UNION     SELECT     *     FROM         [#temp4]     UNION     SELECT     *     FROM         [#temp5] ) a 
like image 77
Chandu Avatar answered Sep 21 '22 12:09

Chandu


insert into temp_UNION select * from ( SELECT     * FROM         [#temp1] UNION SELECT     * FROM         [#temp2] UNION SELECT     * FROM         [#temp3] UNION SELECT     * FROM         [#temp4] UNION SELECT     * FROM         [#temp5] ) 
like image 33
Ovais Khatri Avatar answered Sep 22 '22 12:09

Ovais Khatri