stacking two sql tables (2008) with different column names

12,934

A UNION can be used as long as the datatypes of the columns are the same. It doesn't matter if the column names are different.

SELECT column1
FROM Table1
UNION
SELECT column1
FROM Table2

If you want to know which table the records are coming from, then you can add another field that will distinguish the rows:

SELECT column1, 'Table1' as TableName
FROM Table1
UNION
SELECT column1, 'Table2' as TableName
FROM Table2
Share:
12,934
Admin
Author by

Admin

Updated on July 18, 2022

Comments

  • Admin
    Admin almost 2 years

    I checked this site for code to stack two tables (put the results from one table beneath the results from another) where the column names are different. I know that UNION ALL works when the names are the same.. and I KNOW THAT UNION ALL with an assignment for the column names that are missing from one table works when one table has more info than the other.. but what if the column names are different? like what if in one table the column name is CHP and in another it is "CHILD HEALTH PLUS" and I need those two columns to be stacked on top of one another?