我有一个有趣的情况,我想看看是否有解决方案...我在同一台服务器上的4个数据库中有4个表,所有表都具有相同的结构:
Pnl_IL_2012数据库中的dbo.IL_Membership Pnl_NM_2012数据库中的dbo.NM_Membership
我想将每个表中的聚合数据集合并到一个数据集中,但我正在尝试使用(USE [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
联合所有
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 ')'.
任何人都有办法让联盟全部跨数据库工作?我不需要加入一个工会......
答案 0 :(得分: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'