1

I wanted to add one table below another one in SQL Server.

This is my code:

CREATE TABLE #main_table 
( Scenarios float ,Attribute VARCHAR(50) ,Value float ); 

insert INTO  #main_table  
select * 
FROM 
( SELECT *
FROM #table1
UNION ALL 
SELECT *
FROM #table2) a

But I get an error:

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists

Anyone would know what may be the issue?

user10484829
  • 63
  • 10

3 Answers3

3

You can try below - as union requires equal no of columns in both data set

insert INTO  #main_table  
select * 
FROM 
( SELECT Scenarios,Attribute ,Value
FROM #table1
UNION ALL 
SELECT Scenarios,Attribute ,Value
FROM #table2) a
Fahmi
  • 37,315
  • 5
  • 22
  • 31
2

The columns returned by

SELECT * FROM #table1

and the columns returned by

SELECT * FROM #table2

must be of equal number and have the same type.

George Menoutis
  • 6,894
  • 3
  • 19
  • 43
Alex Leo
  • 2,781
  • 2
  • 13
  • 29
2

use explicit column for union

 insert INTO  #main_table (Scenarios,Attribute,Value) 
    select * 
    FROM 
    ( SELECT col1,col2,col3
    FROM #table1
    UNION ALL 
    SELECT col1,col2,col3
    FROM #table2) a

Union follow below condition

  • Each SELECT statement within UNION must have the same number of columns
  • The columns must also have similar data types
  • The columns in each SELECT statement must also be in the same order
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63