SQL 如何将多个表合并为一张新表?所有列标题都相同且顺序相同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29687166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:31:56  来源:igfitidea点击:

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

sqlsql-server

提问by Maggie

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.

我在 SQL Server 中有 12 个表,它们具有完全相同的列,我想将它们合并到一个全新的表中。我不想删除任何数据/行。

Thanks

谢谢

回答by Giorgi Nakeuri

Use union all:

使用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