Reputation: 681
Is it possible to insert data from select statement into a a dynamically created table? I will not know how many columns are there in select statement until I run the query. It has to create the appropriate number of columns at run time. Thank you, Smith
Upvotes: 1
Views: 351
Reputation: 785
-- This creates temporary table
select * into #newtable from YourTable
select * from #newtable
-- This creates physical table in the DB
select * into newtable from YourTable
select * from newtable
Upvotes: 0
Reputation: 9752
You can use a CTAS pattern for this
USE AdventureWorks
GO
----Create new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
GO
Have a look at This Article on CTAS
Upvotes: 0
Reputation: 32680
Just use the SELECT INTO
syntax:
SELECT *
INTO NewTable
FROM MyTable
WHERE ...
The new table NewTable
will be created with the same columns as your select statement.
Upvotes: 4