Reputation: 5787
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!
Upvotes: 64
Views: 183343
Reputation: 1
In MS Access you can:
SELECT x.* INTO NEWTABLE
FROM (
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2) AS x
It's the same a OMG Ponies's answer except the keyword "AS" is used.
Upvotes: 0
Reputation: 31
Here's one working syntax for SQL Server 2017:
USE [<yourdb-name>]
GO
SELECT * INTO NEWTABLE
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>
Upvotes: 3
Reputation: 1516
INSERT INTO #Temp1
SELECT val1, val2
FROM TABLE1
UNION
SELECT val1, val2
FROM TABLE2
Upvotes: 3
Reputation: 3665
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
Upvotes: 7
Reputation: 181280
You can also try:
create table new_table as
select * from table1
union
select * from table2
Upvotes: 3
Reputation: 332571
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.
Upvotes: 128