Reputation: 13
Hello everyone in SQL if am trying to union two tables in a new one , and am taking the columns names from these table which names its going to take for the new table and why ?
Code:
CREATE TABLE New AS
Select Phonenumber from Data
union
select PhoneNumber from INFO
Incorrect syntax near the keyword 'AS'
Upvotes: 0
Views: 137
Reputation: 1269483
Your query looks correct, assuming your database support create table as
. However, new
could easily be a reserved word in your database. I would recommend a more informative name. Something like this:
CREATE TABLE PhoneNumbers AS
SELECT Phonenumber FROM Data
UNION
SELECT PhoneNumber FROM INFO;
In SQL Server (the tag that was recently added), the correct syntax uses INTO
:
SELECT Phonenumber FROM Data
INTO PhoneNumbers
UNION
SELECT PhoneNumber FROM INFO;
Upvotes: 2
Reputation: 1705
You can use with clause like this:
with cte
as
(
Select Phonenumber from [Data]
union
select PhoneNumber from .[INFO]
)
SELECT Phonenumber INTO dbo.NEW_TABLE
FROM cte;
Upvotes: 0
Reputation: 32003
you could use parenthesis
SELECT x.*
INTO [NEW_TABLE]
FROM
(Select Phonenumber from Data
union
select PhoneNumber from INFO
) x
Upvotes: 1
Reputation: 50163
Your error suggests me SQL Server
DBMS if so then you use SELECT . . . INTO
statement :
SELECT Phonenumber INTO New_table
FROM Data
UNION
SELECT PhoneNumber
FROM INFO;
If the new_table
already exists then you can do instead :
INSERT INTO New_table (Phonenumber)
SELECT Phonenumber INTO New_table
FROM Data
UNION
SELECT PhoneNumber
FROM INFO;
Upvotes: 1
Reputation: 828
For you use union, all the selection groups that you want to use union must have the same number of fields with their own names.
Try:
CREATE TABLE New_table SELECT * FROM (
SELECT Phonenumber FROM Data
UNION
SELECT PhoneNumber FROM INFO
);
Upvotes: 0