Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into an existing temp table in SQL Server

I am trying to execute two select statements into a query that pumps data into a temp table. The first query will have 5 columns while the second query will have only one column.

The first can be achieved by:

Select a.ID AS [a], 
       b.ID AS [b], 
       c.ID AS [c]
INTO #testingTemp
FROM
....

Now I have my second query trying to pump data into #testingTemp:

Select z.ID AS [c]
INTO #testingTemp
FROM
....  

But my problem is There is already an object named #testingTemp in the database?

I tried to search for a solution on the Internet but mostly people are only facing the problem at my first part but apparently nobody trying to expand a temp table on second query?

like image 903
SuicideSheep Avatar asked Jan 07 '14 09:01

SuicideSheep


People also ask

How do I select and insert data into a temp table in SQL?

INSERT INTO SELECT statement reads data from one table and inserts it into an existing table. Such as, if we want to copy the Location table data into a temp table using the INSERT INTO SELECT statement, we have to specify the temporary table explicitly and then insert the data.


3 Answers

Change it into a insert into statement. Otherwise you create the same temp table multiple times and that is not allowed.

Insert into #testingTemp (a,b,c)
Select a.ID AS [a], 
       b.ID AS [b], 
       c.ID AS [c]
FROM
like image 58
schliemann Avatar answered Oct 27 '22 08:10

schliemann


And if you want to insert everything:

INSERT INTO #TempTableName
SELECT * FROM MyTable
like image 20
sandiejat Avatar answered Oct 27 '22 06:10

sandiejat


The second query should just be a normal insert.

    INSERT INTO #testingTemp
    (a,
     b,
     c)
   select etc. 

dont forget to drop the temptable when you are done.

like image 34
Luuk Avatar answered Oct 27 '22 07:10

Luuk