1

Is there a way to create a new table based on a SELECT query in SQL Server ?

I do not want to manually enter all the fields (the table should be auto generated based on the fields in the query).

I already tried :

CREATE TABLE new_table AS (SELECT * FROM ...);

but it did not work.

6 Answers 6

3

You are using the wrong syntax for SQL Server. Instead, try:

SELECT * INTO new_table FROM old_table 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but in this case there is no "old_table". I want to use a runtime SELECT query instead of the "old_table".
Same principle applies: `SELECT * INTO new_table FROM (/*some query*/) t;
3
CREATE TABLE NEW_TABLE
AS
SELECT employee_id, last_name,
FROM
employees

1 Comment

I do not want to manually enter all the fields (the table should be auto generated based on the fields in the query).
1

you can proceed like this

select * into NewTable from  oldtable 

Comments

0

I had to alias the columns in the select, but I would have to think your current query aliases the fields if they don't have name.

select
  *
into #tempabc
from (
  Select 'a' [test]
  union
  Select 'b' [test]
) a

select * from #tempabc

3 Comments

Thanks but both options involve declaring the field names in the Destination Table. Can this be automated ?
The first option didn't specify the columns. I had to alias the field in the select. Also, this question has drastically changed with regards to intent.
Thanks, I replaced the discrete values with a Select * query and it worked !
0
Maybe you could try like this in your query:

create table #temp(@field1 int,@field2 varchar(10))

insert into #temp

       select a,b from tableFrom



select * from #a

then, when you're not using the table again,

drop table #a

4 Comments

question is to create table instantly..not about inserting data into created table
@mohan111, your comment also applies to your own answer. Adding "where 1=3" should solve that little issue.
Doesn't work...DROP Table CCC; CREATE TABLE CCC AS (SELECT * FROM AAA); gives me the error Msg 156, Level 15, State 1, Line 8 Incorrect syntax near the keyword 'AS'.
The SELECT Query will Join multiple tables. This is the whole reason I need the Table to be created on the fly.
-1
SELECT * INTO new_table FROM old_table where 1=2

where condition should be like your query should not return data

1 Comment

This didn't really address the question, but I didn't know you could create an empty table like that. Awesome to know. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.