简体   繁体   English

SQL-UNION ALL大量表

[英]SQL- UNION ALL a large number of tables

I have a large number of tables (some thousands) containing similar data. 我有大量包含相似数据的表(数千个)。 I would like to run some reports from these. 我想从中运行一些报告。 The table names are similar, so I can get a list of table names. 表名相似,因此我可以获得表名列表。

I will likely merge these tables in the future, should be trivial once the select works. 将来我可能会合并这些表,一旦选择成功,这将是微不足道的。

--Getting a list of all tables 
select TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'TableNamePrefix%'
ORDER BY TABLE_NAME

To combine data, I can use UNION ALL, but not sure about how to set up the WHILE/cursor so that the list does not need to be constantly updated. 为了合并数据,我可以使用UNION ALL,但是不确定如何设置WHILE /光标,因此列表不需要不断更新。

Something like 就像是

SELECT * FROM TableNamePrefix00001
UNION ALL
SELECT * FROM TableNamePrefix00002
UNION ALL
SELECT * FROM TableNamePrefix00003
--And so on for all tables in the list

Any help appreciated, thanks. 任何帮助表示赞赏,谢谢。

You can do this with Dynamic SQL 您可以使用Dynamic SQL做到这一点

Declare @SQL varchar(max) =''
Select @SQL = @SQL +'Union All Select * From '+Table_Name+' ' 
  FROM INFORMATION_SCHEMA.TABLES
  WHERE TABLE_NAME LIKE 'TableNamePrefix%'
  ORDER BY TABLE_NAME
Set @SQL = Stuff(@SQL,1,10,'')
Exec(@SQL)
select 'select * from  '+TABLE_NAME +' union all'
FROM
 INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%chd%'
ORDER BY TABLE_NAME

remove last union all 全部删除最后一个联合

所有这些表都具有相同的数据类型和列数,因为如果不是这种情况,那么您将无法使用UNION语句,但是,以这种方式合并所有信息是很奇怪的,您能举一些例子吗?澄清一下。

using your pattern on table name - i got somewhere with 在表格名称上使用您的模式-我在某处

DECLARE @SQL nvarchar(max);

select @SQL =  COALESCE(@SQL , '') + 'SELECT * FROM [' +  TABLE_NAME + ']  UNION ALL ' 
FROM INFORMATION_SCHEMA.TABLES where TABLE_NAME LIKE '%employeedet%';

SELECT @SQL = LEFT(@SQL, LEN(@SQL) - 11);

print @SQL;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM