sql - 具有相同前缀的联合表

sql - union tables with same prefix

我有一组具有相同前缀相同结构的表。我只需要将它们“组合”为一个即可。

use thisdb
declare @maxrow int, @result nvarchar(4000), @tempname nvarchar(20)
set @maxrow = (select count(*) from information_schema.tables where table_schema = 'dbo' and table_name like N'AAbc%')
set @result = ''
set @tempname = 'mytemp'
select @result = @result + case when [row] = 1 then replace([name],'from',concat('into ##',@tempname, ' from')) when [row] = @maxrow then replace([name],'union all','') else [name] end + ' ' 
from 
(select ['table_name,'] union all') as [name], row_number() over(order by table_name asc) as [Row]
from information_schema.tables
where table_schema = 'dbo' and table_name like N'AAbc%') x
execute sp_executesql @result

基本上我从 information_schema.tables 中检索具有特定模式的表,然后摆脱最后一个 union all

以上方法适用于 20-30 个表,因为 @result 不会超过 nvarchar 的限制。但是我很好奇如果表数 N 非常大,如何完成这项工作?或者有更好的方法来处理这个问题?

这应该足够了。 “Union all”替换为“Go”。

declare @script nvarchar(max)

set @script = (
SELECT STUFF(( SELECT  'insert #MyTable(sharedColName1, SharedColName2) select sharedColName1, SharedColName2 from ' + Table_Name + ' Go '
                FROM    ( SELECT DISTINCT
                                    Table_Name
                          FROM      INFORMATION_SCHEMA.Tables
                          where table_Name Like '<prefix_for_tables_with_identical_names>%'
                        ) x
              FOR
                XML PATH('')
              ), 1, 0, '') A
              )
sp_executeSql @script