2015-04-01 87 views
0

我有2个独立的SQL Server数据库想查询和比较结果。如何查询2个SQL数据库并比较结果

例如:

DB1

Select * 
from Customers 
where dtcreated > @startdate 

该查询会给我谁是在特定日期之后创建的客户名单。

然后,我想采取上述结果,并查询另一个数据库(DB2)告诉我哪些上述查询客户仍处于活动状态。

喜欢的东西:

DB2

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

有没有办法做到这一点?

输出:

Number of Records from DB1   Number Active in DB2 
     155         67 

回答

1

您可以通过指定数据库名称和架构+表名做跨数据库查询。

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) 

对不起,但我有点困惑的示例querys和示例输出。但是,使用这种技术,你可以指望任何方式你喜欢

+0

什么是'和a.key = b.key'? – 2015-04-01 11:48:54

+1

好吧,如果你想检查数据库A中是否有客户存在于数据库B中,你需要有一个或一组字段加入,以确保你在谈论同一个客户。更具体地说,您如何知道客户在两个数据库 – 2015-04-01 11:50:06

+0

Tom V.中都是一样的。对不起,我只是想让你知道我在找什么。无论如何,你的信息让我回答我的答案。 a.key = b.key是我尝试的所有内容中缺失的部分。谢谢! – Shmewnix 2015-04-01 12:03:17

0

你可以试试这个:

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

您必须确保'bactive'和'dtcreated'正确编入索引,或者这个查询可能在大型表上运行真的很慢 – 2015-04-01 12:00:41