Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two tables if they are in different schemas

Tags:

sql

sql-server

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
like image 727
vivek kumar luetel Avatar asked Apr 28 '11 04:04

vivek kumar luetel


People also ask

Can we join two tables from different schemas?

yes you can go for it. Need to write the schema name before the table. select Grant premission on it. Source qualifier can join tables from same db with different schemas.

How do you join two tables if there are nothing in common?

Using the “FROM Table1, Table2” Syntax One way to join two tables without a common column is to use an obsolete syntax for joining tables. With this syntax, we simply list the tables that we want to join in the FROM clause then use a WHERE clause to add joining conditions if necessary.


1 Answers

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...

like image 105
gbn Avatar answered Sep 27 '22 17:09

gbn