2016-07-14 46 views
0

使用MS SQL 2008 R2, 我有一個查詢使用cte來構建我所需的輸出。這適用於一個數據庫,但現在我需要在多個數據庫中提取相同的查詢,並將所有這些結果返回到一個結果集中。沒有極端的細節我有:建立在多個數據庫上的CTE上的UNION SQL查詢

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

我得到的投訴「;」和工會/工會。如何將所有數據庫的所有最終選擇語句輸出都放到1個結果集中。

回答

0

CTE不以這種方式工作..

解決問題創建全局臨時表和填充表,並在年底做選擇。

即樣本假設有兩個列列1列2和從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 ; 
+0

這正是我需要的產生謝謝你,沒想到使用全局臨時表。現在我只需要讓它與SSRS一起工作:)感謝您的幫助! –