views:

52

answers:

3

Hi, 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!

+4  A: 

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.

OMG Ponies
A: 

You can also try:

create table new_table as
select * from table1
union
select * from table2
Pablo Santa Cruz
Not SQL Server syntax.
Shannon Severance
A: 
select *
into new_table
from table_A
UNION
Select * 
From table_B

This only works if Table_A and Table_B have the same schemas

Jim
You can use three (and four if the table is on a Linked Server instance) name format to access other schemas and/or databases.
OMG Ponies