Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT INTO USING UNION QUERY

I want to create a new table in SQL Server with the following query. I am unable to understand why this query doesn't work.

Query1: Works

SELECT * FROM TABLE1 UNION SELECT * FROM TABLE2  

Query2: Does not Work. Error: Msg 170, Level 15, State 1, Line 7 Line 7: Incorrect syntax near ')'.

SELECT * INTO [NEW_TABLE] FROM ( SELECT * FROM TABLE1 UNION SELECT * FROM TABLE2 ) 

Thanks!

like image 505
Sekhar Avatar asked Oct 25 '10 20:10

Sekhar


People also ask

Can we use UNION in SELECT query?

The UNION operator is used to combine the data from the result of two or more SELECT command queries into a single distinct result set. This operator removes any duplicates present in the results being combined.

What is SQL UNION SELECT?

The SQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION must have the same number of fields in the result sets with similar data types.


1 Answers

You have to define a table alias for a derived table in SQL Server:

SELECT x.*    INTO [NEW_TABLE]   FROM (SELECT * FROM TABLE1         UNION         SELECT * FROM TABLE2) x 

"x" is the table alias in this example.

like image 145
OMG Ponies Avatar answered Sep 29 '22 02:09

OMG Ponies