繁体   English   中英

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

暂无
暂无

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

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