I need to make a dynamic query that will span across 2 databases.
Db1: Table1
Db2: Table2
First I will select some items based on hard coded ID's from table1 in db1.
Select *
from Db1.Table1
where Id = 123
Table1
has a column called CityId
that is part of Db2.Table2
. So when inserting new items in Db2.Table2
, the CityId
is an Identity column.
Now I need something like:
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?
If I understand correctly, you just need to use three-part naming:
select t2.*
from Db2..Table2 t2
where t2.CityId in (select t1.CityID from Db1..Table1 t1 where t1.Id = 123)
The default schema name is usually dbo
, so you can be more explicit:
select t2.*
from Db2.dbo.Table2 t2
where t2.CityId in (select t1.CityID from Db1.dbo.Table1 t1 where t1.Id = 123)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.