How to combine SELECT and INSERT commands into a non existent table in SQL Server?

10,156

Solution 1

You got two options. First one is to create your temp table and then use INSERT INTO ... SELECT, like this:

CREATE TABLE #temp (
  Col1 ...
);

INSERT INTO #temp
SELECT * FROM OtherTable;

The second option is to insert directly in a new temp table:

SELECT  *
INTO    #temp
FROM    OtherTable;

Big difference is that using method 1, you need to specify all the columns in your temp table in advance. Method 2 gives you a temp table that automatically has all the columns of your OtherTable.

Solution 2

You want to insert into a table that doesn't yet exist? Your syntax was close. See here.

SELECT * INTO #BrandNewTempTable FROM MyTable 

Solution 3

Your temporary table needs have the same fields of your origin table

If not you need specify all fields like code below:

INSERT INTO TEMPORARY_TABLE (field1, field1, field1)
SELECT (field1, field1, field1) FROM YOUR_TABLE;
Share:
10,156
2hamed
Author by

2hamed

Go/Java/Kotlin/PHP

Updated on June 15, 2022

Comments

  • 2hamed
    2hamed almost 2 years

    How does one combine the SELECT and INSERT INTO commands and insert the results into a temporary table in SQL Server?

    Something like this:

    INSERT INTO #TempTable 
        SELECT * FROM MyTable;
    
  • GTSouza
    GTSouza almost 12 years
    interesting that I did not know, nice one
  • 2hamed
    2hamed almost 12 years
    Thanks, that's what I was looking for.
  • 2hamed
    2hamed almost 12 years
    One question. Can this syntax be used in MySql as well?
  • Tony
    Tony almost 12 years
    @EdwinDrood - A quick Google shows the syntax has been supported by MySQL since version 3.23 (dev.mysql.com/doc/refman/4.1/en/…)