-1

我对整个 SQL DB 迁移的东西真的很陌生,我已经准备好学习了。

我有 2 个不同的数据库,它们都有一个用户表,HtUser在一个目标数据库和HTUser源数据库中调用。

我想创建一个脚本,该脚本从源数据库中的特定列firstName, lastName, email和目标数据库中的特定列复制数据,FirstName, LastName, Email并且“特殊字段”UserName包含 ch + 两个字母firstName来自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;
4

3 回答 3

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
    );
于 2013-03-28T15:20:11.180 回答
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 
于 2013-03-28T15:20:43.070 回答
1

您是否查看过 SQL Server 2005 及更高版本附带的 TABLEDIFF 实用程序?可以在这里这里找到很好的例子

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.
于 2013-03-28T16:51:19.507 回答