2013-03-28 66 views
-1

我在這整個SQL數據庫遷移的東西真的很新,我準備學習。如何將數據庫表中的數據遷移到另一個SQL?

我有2個不同的數據庫,他們都有一個用戶表,在源數據庫中稱爲HtUser在一個目標數據庫和HTUser

我想創建一個腳本,是複製源數據庫從特定列中的數據,這將是firstName, lastName, email和我的目的地分貝,這將是FirstName, LastName, Email和「專業」 UserName包含從firstName CH +兩個字母和lastName三個。

INSERT INTO HolidayTracker.dbo.HtUser(FirstName,LastName,Email,UserName,AdAccount,AdDomain) 
SELECT firstName,lastName,email,'CH'+LEFT(firstName,2)+LEFT(lastName,3),'EUROPE\'+LEFT(firstName,2)+LEFT(lastName,3),'' 
FROM HolidayTracker.dbo.HTUser U1 
WHERE NOT EXISTS (SELECT 1 FROM HolidayTracker.dbo.HTUser U2 WHERE U2.FirstName = U1.firstName AND U2.LastName = U1.lastName AND U2.email = U1.Email); 








INSERT INTO HolidayTracker.dbo.HtUser(FirstName,LastName,Email,UserName,AdAccount,AdDomain) 
SELECT firstName,lastName,email,'CH'+LEFT(firstName,2)+LEFT(lastName,3),'EUROPE\'+LEFT(fistName,2)+LEFT(lastName,3),'' 
FROM HolidayTracker.dbo.HTUser u1 
    LEFT JOIN HolidayTracker.dbo.HtUser u2 ON u1.firstName = u2.FirstName AND u1.lastName = u2.LastName AND u1.email = u2.Email 
    WHERE u2.FirstName IS NULL 
    AND u2.LastName IS NULL 
    AND u2.Email IS NULL; 
+0

你到目前爲止寫了什麼? – Axarydax

回答

6

假設您有2個名爲db1和db2的數據庫,這可能會起作用。

INSERT INTO db2.dbo.HTUser (FirstName, LastName, Email, UserName) 
SELECT firstName, lastName, email, 'CH' + LEFT(firstName, 2) + LEFT(lastName, 3) 
FROM db1.dbo.HtUser U1 
    LEFT JOIN db2.dbo.HTUser U2 ON U1.firstName = U2.FirstName 
     AND U1.lastName = U2.LastName 
     AND U1.email = U2.Email 
WHERE U2.firstName IS NULL 
    AND U2.lastName IS NULL 
    AND U2.email IS NULL; 

該版本將從db1.dbo.HtUer中複製db2.dbo.HTUser中不存在的用戶。

而且使用首選NOT EXISTS(感謝@AaronBertrand!)版本:

INSERT INTO db2.dbo.HTUser (FirstName, LastName, Email, UserName) 
SELECT firstName, lastName, email, 'CH' + LEFT(firstName, 2) + LEFT(lastName, 3) 
FROM db1.dbo.HtUser U1 
WHERE NOT EXISTS 
    (
     SELECT 1 
     FROM db2.dbo.HTUser U2 
     WHERE U2.firstName = U1.FirstName 
      AND U2.lastName = U1.LastName 
      AND U2.email = U1.Email 
    ); 
+1

感謝您浪費您的時間來回答我的問題,你幫我分配! – Mingebag

+3

如果數據庫在同一實例上,它們如何具有相同的名稱? Unpossible。 –

+0

Sry如果我打擾你,但當我執行此查詢時,它只是再次添加現有用戶 – Mingebag

1

您可以在這一個使用INSERT INTO...SELECT聲明。

INSERT INTO db1.HtUser (firstName, lastName, email, [username]) 
SELECT firstName, lastName, email, 
     'ch' + SUBSTRING(firstName,1,2) + SUBSTRING(lastname,1,3) 
FROM db2.HtUser 
1

你看過SQL Server 2005自帶的TABLEDIFF實用程序嗎?很好的例子可以發現herehere

tablediff.exe utility features 

Comparison between two tables from SQL Server instance. 
Row by row fast comparision. 
**Perform column level comparison.** 
Easily generate change script between production and development SQL server instances. 
Log result can be captured as output file or database table. 
Location: 

tablediff.exe is available on SQL Server instance at 
"<DriveLetter>:\Program Files\Microsoft SQL Server\90\COM\TableDiff.exe" 

<DriveLetter> is the hard drive where SQL Server instance is installed. 
相關問題