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

UNION SQL Query built on CTE over multiple databases

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

;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+

我收到关于“;”的投诉和 union/union 全部。如何将所有数据库的所有最终 select 语句输出到 1 个结果集中。

CTE 这样不行..

解决问题创建全局临时文件 table 并填充 table,最后执行 select .

即样本假设有两列column1和column2是从cte3生成的

    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 ;