如何从SQL Server中的多个数据库连接重复的表

时间:2016-09-20 14:02:13

标签: sql-server database tsql ssms

我正在尝试选择一个大表,该表结合了同一服务器上多个数据库中多个表的名称,电子邮件和帐户名。我有4个数据库,它们包含相同的表但具有不同的(区域特定的)数据。

第一个数据库的Ex:

SELECT t1.FirstName,
       t1.LastName,
       t1.Email,
       t1.AccountID,
       t2.AccountName,
       t2.AccountID
INTO NewContactsTable
FROM DataBase1.dbo.Contacts t1
INNER JOIN DataBase1.dbo.Accounts t2 ON t2.AccountID = t1.AccountID

所以我想做同样的事情(加入Contacts和Accounts表),但在一个查询中还有3个其他数据库(DataBase2,DataBase3,DataBase4)。

1 个答案:

答案 0 :(得分:2)

查询可能如下所示:

SELECT t1.FirstName, t1.LastName, t1.Email, t1.AccountID,
       t2.AccountName, t2.AccountID
INTO NewContactsTable
FROM DataBase1.dbo.Contacts t1 INNER JOIN
     DataBase1.dbo.Accounts t2
     ON t2.AccountID = t1.AccountID
UNION ALL
SELECT t1.FirstName, t1.LastName, t1.Email, t1.AccountID,
       t2.AccountName, t2.AccountID
FROM DataBase2.dbo.Contacts t1 INNER JOIN
     DataBase2.dbo.Accounts t2
     ON t2.AccountID = t1.AccountID
UNION ALL
SELECT t1.FirstName, t1.LastName, t1.Email, t1.AccountID,
       t2.AccountName, t2.AccountID
FROM DataBase3.dbo.Contacts t1 INNER JOIN
     DataBase3.dbo.Accounts t2
     ON t2.AccountID = t1.AccountID
UNION ALL
SELECT t1.FirstName, t1.LastName, t1.Email, t1.AccountID,
       t2.AccountName, t2.AccountID
FROM DataBase4.dbo.Contacts t1 INNER JOIN
     DataBase4.dbo.Accounts t2
     ON t2.AccountID = t1.AccountID;

但是,我倾向于先创建表,然后分别插入每个查询中的行。