【问题标题】:SQL Server query - 2 databasesSQL Server 查询 - 2 个数据库
【发布时间】:2018-04-15 15:03:25
【问题描述】:

我需要进行跨 2 个数据库的动态查询。

Db1:表 1

Db2:表 2

首先,我将根据 db1 中 table1 的硬编码 ID 选择一些项目。

Select * 
from Db1.Table1 
where Id = 123

Table1 有一个名为CityId 的列,它是Db2.Table2 的一部分。所以在Db2.Table2 中插入新项目时,CityId 是一个标识列。

现在我需要类似的东西:

use Db1
go

select * 
from Db1.Table1 
where Id = 123

use Db2
go

select * 
from Db2.Table2 
where CityId in (select CityID 
                 from Db1.Table1 
                 where Id = 123)   // how can I solve this cross db query?

【问题讨论】:

  • 3 部分名称:database.schema.table
  • 该死,我忘记了架构......
  • 正常的东西,周末工作。我要睡午觉了!
  • 完美运行!!

标签: sql sql-server


【解决方案1】:

如果我理解正确,你只需要使用三部分命名:

select t2.*
from Db2..Table2 t2
where t2.CityId in (select t1.CityID from Db1..Table1 t1 where t1.Id = 123) 

默认架构名称通常为dbo,因此您可以更明确:

select t2.*
from Db2.dbo.Table2 t2
where t2.CityId in (select t1.CityID from Db1.dbo.Table1 t1 where t1.Id = 123) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2013-01-30
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多