2012-12-11 51 views
2

我有一個有趣的情況,我想查看是否有解決方案...我在同一臺服務器上的4個數據庫中有4個表,全部具有相同的結構:在數據庫之間使用「Union All」查詢

dbo.IL_Membership在Pnl_NM_2012數據庫Pnl_IL_2012數據庫 dbo.NM_Membership

我想聚集的數據集從每個表合併成一個數據集,但我試圖利用(使用[Pnl_IL_2012] - > Go)構造嘗試獲取每個聚合查詢的數據。

select * from 
(USE [Pnl_IL_2012] 
GO 
select 'IL' as PlanID, sum(Contracts_Hlth) as PROD_Contracts_Hlth from dbo.IL_Membership where [month] between '2012-09-01' and '2012-10-31') Q1 

UNION ALL

select * from 
(USE [Pnl_NM_2012] 
GO 
select 'NM' as PlanID, sum(Contracts_Hlth) as PROD_Contracts_Hlth from dbo.NM_Membership where [month] between '2012-09-01' and '2012-10-31') Q2 

我得到這些錯誤:

Msg 156, Level 15, State 1, Line 2 
Incorrect syntax near the keyword 'USE'. 
Msg 102, Level 15, State 1, Line 1 
Incorrect syntax near ')'. 
Msg 156, Level 15, State 1, Line 5 
Incorrect syntax near the keyword 'USE'. 
Msg 102, Level 15, State 1, Line 1 
Incorrect syntax near ')'. 

任何人有辦法讓工會所有跨數據庫的工作?我不需要聯合只是一個聯合...

回答

2

GO表示一個批處理結束,所以這不能用於查詢中。

相反,使用引用表的three part name

Pnl_IL_2012.dbo.IL_Membership 

給你下面的查詢:

select 'IL' as PlanID, sum(Contracts_Hlth) as PROD_Contracts_Hlth 
from Pnl_IL_2012.dbo.IL_Membership 
where [month] between '2012-09-01' and '2012-10-31' 

union all 

select 'NM' as PlanID, sum(Contracts_Hlth) as PROD_Contracts_Hlth 
from Pnl_NM_2012.dbo.IL_Membership 
where [month] between '2012-09-01' and '2012-10-31' 
+0

太謝謝你了!我剛剛使用了它,這正是我需要的。 – digitalcb