Search code examples
sql-serverdatabasesql-inserttemp-tables

Insert data into temp table using select statement?


I want to insert data manually into temporary table from select statement:

  Select into #temp from (select 1,2
    Union 
    select 2,4 
    Union 
    Select 8,12) as b

Solution

  • You need to give columns a name (here I have named the columns a and b):

    Select a, b into #temp 
    from 
    (
         select a = 1, b = 2 
         Union 
         select 2, 4 
         Union 
         Select 8, 12
    ) as t
    
    select * from #temp
    
    a   b
    -----
    1   2
    2   4
    8   12
    

    Only the first SELECT clause of a UNION needs the explicit column names.