【问题标题】:Using "Union All" with Queries Between Databases对数据库之间的查询使用“Union All”
【发布时间】:2012-12-12 00:45:17
【问题描述】:

我有一个有趣的情况,我想看看是否有解决方案...我在同一台服务器上的 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 ')'.

谁有办法让 union all 跨数据库工作?我不需要加入只是一个工会......

【问题讨论】:

    标签: sql-server-2008 multiple-databases union-all


    【解决方案1】:

    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'
    

    【讨论】:

    • 非常感谢!我刚刚使用了它,这正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2012-03-06
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多