我有600个表要执行UNION ALL
查询。不幸的是,每个表中列的顺序各不相同,但是它们始终具有相同的名称-例如:
表1
Item, Cost, ID, Code, Location
表2
Cost, Id, Code, Location, Item
表3
Id, Code, Cost, Item, Location
是否有写联合查询的方法,无论原始表中的顺序如何,它都将与列名匹配?
A,不。 UNION ALL
按位置而不是按名称。但是,您可以生成列:
select string_agg(column_name, ', ')
from information_schema.columns
where table_name = ? and
table_schema = ?;
然后您可以将列表插入代码中。
以下代码将以任何顺序查找具有指定列的所有表。然后,它将使用该列表组装一个查询,该查询将所有表中的数据与每个表中的列以相同的顺序进行合并。
declare @Query as NVarChar(max);
-- Quote column names here as needed:
declare @Prefix as NVarChar(64) = N'select Id, Item, Code, Location, Cost from ';
declare @Suffix as NVarChar(64) = NChar( 13 ) + NChar( 10 ) + N'union all' + NChar( 13 ) + NChar( 10 );
with
TargetTables as (
-- All of the table which have the specified list of columns, regardless of column order.
select T.Table_Schema, T.Table_Name
from Information_Schema.Tables as T inner join
Information_Schema.Columns as C on C.Table_Schema = T.Table_Schema and C.Table_Name = T.Table_Name
where C.Column_Name in ( 'Id', 'Item', 'Code', 'Location', 'Cost' ) -- Do not quote column names here.
group by T.Table_Schema, T.Table_Name
having Count( Distinct C.Column_Name ) = 5
)
-- Build the query by inserting @Prefix and @Suffix around each properly quoted table schema and name.
select @Query = (
select @Prefix + QuoteName( Table_Schema ) + '.' + QuoteName( Table_Name ) + @Suffix
from TargetTables
order by Table_Schema, Table_Name
for XML path(''), type).value('.[1]', 'VarChar(max)' );
-- Clean up the tail end of the query.
select @Query = Stuff( @Query, DataLength( @Query ) / DataLength( N'-' ) - DataLength( @Suffix ) / DataLength( N'-' ) + 1, DataLength( @Suffix ) / DataLength( N'-' ), N';' );
-- Display the resulting query.
-- In SSMS use Results To Text (Ctrl-T) to see the query on multiple lines.
select @Query as Query;
-- Execute the query. NB: The parentheses are required.
execute ( @Query );
根据您的需求,您可以运行一次以获取查询,然后将结果语句剪切并粘贴到适当的位置,例如存储过程或视图,也可以让它生成动态SQL并执行它。
[其他验证,例如不包括系统表,留给读者。