Use of Temporary table for storing output from two or more different Queries

  • Hey There,

    I have two different stored procedures or queries, say Query1 and Query2; I want to store the output from Query1 and Query2 into a temporary table #Table1.

    Can anyone suggest me how I can insert the values into #Table1.

    Thank You

  • Given that Query1 and Query2 give the same output columns, you coud do something like:

    INSERT #table1 EXEC Query1

    INSERT #table1 EXEC Query2

    -- Gianluca Sartori

  • Hi,

    I tried to insert into #Table1 and I am getting an error as :

    The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.

    Ofcourse the columns from two queries combined give the columns of #Table1.

  • The message you are getting means that Table1 has a different number of columns from the output of Query1.

    If you just want to insert some columns, declare it explicitly:

    INSERT #Table1 (column1, column2, ..., columnN) EXEC Query1

    -- Gianluca Sartori

  • In #Table1, the columns are declared explicitly taking in mind the total number of columns combinedly from Query1 and Query2.

  • I see. You're trying to do something impossible.

    Try this instead: create two temp tables (eg. #table1 and #table2), insert into each table the results from the two procedures and join the temp tables.

    INSERT #Table1 EXEC Query1

    INSERT #Table2 EXEC Query2

    SELECT *

    FROM #Table1 AS A

    INNER JOIN #Table2 AS B

    ON A.column1 = B.column1

    -- Gianluca Sartori

  • It seems this would go as per my requirement, but I wanted that impossible way. 🙂

    Thank you

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply