[英]How to join two tables from two different sql server databases in a simple but complete c# project?
[英]How to join repeated tables from multiple databases in SQL Server
我正在嘗試選擇一個大表,該表將同一服務器上多個數據庫中多個表的名稱,電子郵件和帳戶名組合在一起。 我有4個數據庫,它們包含相同的表,但具有不同的(特定於區域的)數據。
例如第一個數據庫:
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)。
查詢可能如下所示:
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;
但是,我傾向於先創建表,然后分別插入每個查詢的行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.