Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine multiple tables into one new table? All of the columns headers are the same and in the same order

Tags:

sql

sql-server

I have 12 tables in SQL Server with the exact same columns that I would like to combine into one brand new table. I don't want any data/rows deleted.

Thanks

like image 640
Maggie Avatar asked Apr 16 '15 22:04

Maggie


1 Answers

Use union all:

insert into NewTable(col1, col2)
select col1, col2 
from(
    select col1, col2 from Table1
    union all
    select col1, col2 from Table2
    union all
    select col1, col2 from Table3
    .....
)t

You can create new table while selecting like:

select col1, col2 
into NewTable
from(
    select col1, col2 from Table1
    union all
    select col1, col2 from Table2
    union all
    select col1, col2 from Table3
    .....
)t
like image 71
Giorgi Nakeuri Avatar answered Sep 29 '22 10:09

Giorgi Nakeuri