创建一个新表,该表将具有相同列结构的多个表合并(UNION)

时间:2019-04-30 23:27:48

标签: sql-server

我收到此错误:关键字“选择”附近的语法不正确。

尝试执行此操作时:

Create Tables new_table
Select * , 'XXX1' as XField
From old_table1
UNION ALL
Select * , 'XXX2' as XField
From old_table2
UNION ALL
Select * , 'XXX3' as XField
From old_table3

我尝试了来自stackoverflow的其他建议,这些建议与使用union创建新表有关,但解决方案无效

Create Tables new_table
Select * , 'XXX1' as XField
From old_table1
UNION ALL
Select * , 'XXX2' as XField
From old_table2
UNION ALL
Select * , 'XXX3' as XField
From old_table3

我希望(经过长时间的处理,我使用UNION ALL之后),我的结果将是一个包含所有字段和用户定义字段的新表。

2 个答案:

答案 0 :(得分:1)

创建一个view

create view new_table as
select ...
union all
select ...
etc

答案 1 :(得分:1)

您需要SELECT ... INTO

select * into new_table
from (
  Select * , 'XXX1' as XField
  From old_table1
  UNION ALL
  Select * , 'XXX2' as XField
  From old_table2
  UNION ALL
  Select * , 'XXX3' as XField
  From old_table3
) t;