Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a table from select query result in SQL Server 2008 [duplicate]

People also ask

How can we create duplicate table using query in SQL Server?

Right-click the table you wish to duplicate, point to Script Table as, then point to CREATE to, and then select New Query Editor Window. Change the name of the table. Remove any columns that are not needed in the new table. Select Execute to create the new table.

How do you create a new table from SQL query results?

If you would like to create a new table, the first step is to use the CREATE TABLE clause and the name of the new table (in our example: gamer ). Then, use the AS keyword and provide a SELECT statement that selects data for the new table.


Use following syntax to create new table from old table in SQL server 2008

Select * into new_table  from  old_table 

use SELECT...INTO

The SELECT INTO statement creates a new table and populates it with the result set of the SELECT statement. SELECT INTO can be used to combine data from several tables or views into one table. It can also be used to create a new table that contains data selected from a linked server.

Example,

SELECT col1, col2 INTO #a -- <<== creates temporary table
FROM   tablename
  • Inserting Rows by Using SELECT INTO

Standard Syntax,

SELECT  col1, ....., col@      -- <<== select as many columns as you want
        INTO [New tableName]
FROM    [Source Table Name]

Please be careful, MSSQL: "SELECT * INTO NewTable FROM OldTable"

is not always the same as MYSQL: "create table temp AS select.."

I think that there are occasions when this (in MSSQL) does not guarantee that all the fields in the new table are of the same type as the old.

For example :

create table oldTable (field1 varchar(10), field2 integer, field3 float)
insert into oldTable (field1,field2,field3) values ('1', 1, 1)
select top 1 * into newTable from oldTable

does not always yield:

create table newTable (field1 varchar(10), field2 integer, field3 float)

but may be:

create table newTable (field1 varchar(10), field2 integer, field3 integer)

Please try:

SELECT * INTO NewTable FROM OldTable

Try using SELECT INTO....

SELECT ....
INTO     TABLE_NAME(table you want to create)
FROM source_table

Select [Column Name] into [New Table] from [Source Table]