Search code examples
sqlsql-servertemp-tables

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?


Solution

  • 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