在两个数据库之间传输数据并同步检查不重复的值

时间:2012-02-22 11:24:27

标签: sql sql-server-2008 tsql

我想从差异数据库中的两个表之间传输一些数据但是源表在PostalCode列中有一些重复的值,我在PostalCode列上创建了带有UK的目标表,并且在传输脚本中需要同步检查以不插入之前插入的值,这是我的示例脚本:

INSERT INTO [Target]
(
    [FirstName],
    [LastName],
    [PostalCode],
)
(
SELECT  
[Sc].[FirstName],
[Sc].[LastName],
CASE 
WHEN 'Check for not repeated before' THEN [Sc].[PostalCode]
ELSE CAST(1000000000 + ROW_NUMBER() OVER(ORDER BY [Sc].[FirstName]) AS CHAR(10)) END

FROM [Source] AS [Sc]
);

那么,你有什么建议来处理这个问题?

修改

有没有办法用for或cursor编写脚本?我的意思是异步检查重复的值?

2 个答案:

答案 0 :(得分:1)

我强烈建议不要将两条信息混合到一个字段中。

相反,只需要一个额外的列,可能称为DuplicationID

INSERT INTO [Target]
(
    [FirstName],
    [LastName],
    [PostalCode],
    [DuplicationID]
)
SELECT  
    [Sc].[FirstName],
    [Sc].[LastName],
    [Sc].[PostalCode],
    ROW_NUMBER() OVER (PARTITION BY [Sc].[PostalCode] ORDER BY [Sc].[PostalCode])
FROM 
    [Soruce] AS [Sc]

DuplicationID为1的任何记录都被计为该邮政编码的第一个实例。任何其他值都是重复的。

答案 1 :(得分:0)

也许是这样的:

;WITH CTE AS
(
    SELECT
        COUNT(*) OVER(PARTITION BY [PostalCode]) AS NbrOf,
        ROW_Number() OVER
                    (
                        PARTITION BY [PostalCode] 
                        ORDER BY [PostalCode]
                ) AS RowNbr
        [FirstName],
        [LastName],
        [PostalCode],
    FROM
        [Source] AS [Sc]
)
INSERT INTO [Target]
(
    [FirstName],
    [LastName],
    [PostalCode],
)
SELECT  
    [Sc].[FirstName],
    [Sc].[LastName],
    CASE 
        WHEN CTE.NbrOf>1 
        THEN CAST(1000000000+CTE.RowNbr AS VARCHAR(10))
        ELSE [Sc].[PostalCode] 
    END
FROM 
    CTE