Shmewnix
Shmewnix

Reputation: 1573

How to Query 2 SQL databases and compare results

I have 2 separate SQL Server databases i'd like to query and compare the results.

For example:

DB1

Select * 
from Customers 
where dtcreated > @startdate

This query will give me a list of customers who were created after a specific date.

I would then like to take the results above, and query another database (DB2) to tell me which of the above query customers are still active.

Something like:

DB2

Select * 
From Customers
Where bactive = 'True'
      (and exists in DB1 query)

Is there a way to do this?

Output:

Number of Records from DB1            Number Active in DB2
        155                                   67

Upvotes: 0

Views: 91

Answers (2)

Tom V
Tom V

Reputation: 1496

You can do cross-database queries by specifying the databasename and the schema + table name.

Select * 
From Customers b
Where bactive = 'True'
and exists
(Select 'x' from 
database1.dbo.Customers A
where a.dtcreated > @startdate
and a.key = b.key)

I'm sorry but i'm a bit confused by the example querys and example output. But using this technique you can count any way you like

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172418

You can try this:

Select * 
From db2.dbo.Customers
Where bactive = 'True'
and exists(Select * from db1.dbo.Customers where dtcreated > @startdate)

Upvotes: 0

Related Questions