SQL Server查询 - 2个数据库

时间:2018-04-15 15:03:25

标签: sql sql-server

我需要制作一个跨越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?

1 个答案:

答案 0 :(得分:0)

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

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) 
相关问题