我们有一个设计糟糕的数据库,其中包含每周生成新表的程序,并且已经这样做了几年。它有一个SQL脚本,通过各种表上的查询获得200多列数据,将它们全部转储到一个名为Selections的表中,然后在完成后你必须手动重命名该表(Selections_Week001) ,Selections_Week002等)每周。现在我们有大约100多张桌子。我想要做的是将所有数据放入一个表中,其中一列指示其原始源表(001,002等),因此我可以删除所有这些单独的表。有没有办法使用一些SQL脚本,或者我将不得不手动编辑和运行100个附加查询?
答案 0 :(得分:1)
试试这个,因为我在测试数据方面做得很好:
select *
into Selections_Total
from Selections_Week001
where 1=0
alter table Selections_Total
add Original_Table varchar(64)
--select * From Selections_Total
declare @sql varchar(max)
select @sql = COALESCE(@sql + ' UNION ALL select *, ''' + name + ''' from ', 'select *, ''' + name + ''' from ') + name
from sys.tables where name like 'Selections_Week%'
--select @sql
insert into Selections_Total
exec(@sql)
UPD:首先错过了with a column indicating its original source table
。现在修好了。