如何在 SQL 服务器中连接来自多个数据库的重复表
How to join repeated tables from multiple databases in SQL Server
我正在尝试 select 合并到一个大型 table 中,该大型 table 将来自同一服务器上多个数据库中多个 table 的姓名、电子邮件和帐户名组合在一起。我有 4 个包含相同 table 但具有不同(特定于区域)数据的数据库。
例如第一个数据库:
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
所以我想做与上面相同的事情(加入联系人和帐户 tables),但在单个查询中使用其他 3 个额外的数据库(DataBase2、DataBase3、DataBase4)。
查询可能如下所示:
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;
但是,我倾向于先创建 table,然后分别插入来自每个查询的行。
我正在尝试 select 合并到一个大型 table 中,该大型 table 将来自同一服务器上多个数据库中多个 table 的姓名、电子邮件和帐户名组合在一起。我有 4 个包含相同 table 但具有不同(特定于区域)数据的数据库。
例如第一个数据库:
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
所以我想做与上面相同的事情(加入联系人和帐户 tables),但在单个查询中使用其他 3 个额外的数据库(DataBase2、DataBase3、DataBase4)。
查询可能如下所示:
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;
但是,我倾向于先创建 table,然后分别插入来自每个查询的行。