UNION SQL查询基于多个数据库的CTE构建

时间:2016-07-14 14:43:51

标签: database sql-server-2008 common-table-expression unions

使用MS SQL 2008 R2, 我有一个使用cte来构建我想要的输出的查询。这适用于一个数据库但现在我需要在多个数据库上提取相同的查询并将所有这些结果返回到一个结果集中。没有极端的细节,我有:

;with cte1 as ( my query from db1),
cte2 as ( another query from cte1),
cte3 as ( yet another one from cte2)
Select 'db1.Name' as dbName, * from cte3

这为我提供了第一列具有关联数据库名称所需的数据。现在我需要运行30多个数据库,所有数据库都具有相同的模式和相同的输出,但是当我尝试这个时:

;with cte1 as ( my query from db1),
cte2 as ( another query from cte1),
cte3 as ( yet another one from cte2)
Select 'db1.Name' as dbName, * from cte3

Union (or Union All)

;with cte1 as ( my query from db2),
cte2 as ( another query from cte1),
cte3 as ( yet another one from cte2)
Select 'db2.Name' as dbName, * from cte3

Union (or Union All)

... till we reach the 30+

我抱怨“;”和工会/工会全部。如何将所有数据库的所有最终select语句输出到1个结果集中。

1 个答案:

答案 0 :(得分:0)

CTE不能这样工作..

解决问题创建全局临时表并填充表,最后选择。

即假设从cte3

生成两列column1和column2的样本
    CREATE TABLE ##result
    ( dbname varchar(50);
      column1 varchar(50),
      column2 varchar(50))


    ;with cte1 as ( my query from db1),
    cte2 as ( another query from cte1),
    cte3 as ( yet another one from cte2)

    INSERT INTO ##result (dbname ,column1 ,column2)
    Select 'db1.Name' as dbName, * into ##result from cte3

     ;with cte1 as ( my query from db1),
    cte2 as ( another query from cte1),
    cte3 as ( yet another one from cte2)

    INSERT INTO ##result (dbname ,column1 ,column2)
    Select 'db1.Name' as dbName, * into ##result from cte3


    select * from  ##result ;