9

I have two different schemas in SQL Server (say S1, S2). And two tables in those schemas(say S1.Table1, S2.Table2). I want to query these two tables from schema S1.

Both S1 and S2 are in SQL Server 2005 databases. I want to do something like this:

select T1.Id
  from S1.Table1 T1
     , S2.Table2 T2 
 Where T1.Id = T2.refId
bluish
  • 24,718
  • 26
  • 114
  • 174
vivek kumar luetel
  • 107
  • 1
  • 4
  • 10

3 Answers3

7

Use 3 part object names to specify the database: I assume you mean "database" not "schema" (in say the Oracle sense)

select T1.Id
from 
  DB1.schema.Table1 T1
 JOIN
   DB2.schema.Table2 T2 ON T1.Id = T2.refId

Note the better way of doing JOINs...

gbn
  • 408,740
  • 77
  • 567
  • 659
  • 2
    @Greg Randall: clarity, less chance to feck up, filter/join separation, semantically correct with OUTER JOINS, later ANSI standard (1992), deprecated `*=` and `=*` (OUTER JOIN-in-WHERE) syntax... http://stackoverflow.com/questions/5654278/sql-join-is-there-a-difference-between-using-on-or-where/5654338#5654338 – gbn Apr 28 '11 at 04:56
  • Yeah the only time I use it is for outer joins. There isn't a performance difference, I just find it easier to read in ANSI 89, even if it makes my code more error prone. – Greg Randall Apr 28 '11 at 20:46
3
Select T1.Id

FROM

s1.Table1 T1

JOIN

s2.Table2 T2

WHERE

T1.Id = T2.refId;

This is the way to do your query on MySQL. I would assume it also works in Oracle 11g.

Jude Fisher
  • 10,919
  • 7
  • 47
  • 88
Anthony
  • 69
  • 5
2

You didn't mention if the DBs were on the same server. If yes, you can follow the answer above. If not, you will need to create a linked server one of the servers, and then you can reference the linked server via


select T1.Id
  from [linkedservername].DB1.Schema.Table1 T1
     , S2.Table2 T2 
 Where T1.Id = T2.refId

M.R.
  • 4,637
  • 2
  • 34
  • 79