【问题标题】:How to treat unique constraint violations in a data migration script?如何处理数据迁移脚本中的唯一约束违规?
【发布时间】:2013-04-24 18:55:07
【问题描述】:

在这里,我试图将一些数据从表列迁移到一个全新的表,其中目标列具有唯一约束。基本上我正在尝试:

INSERT INTO FooTable VALUES (SELECT BarTable.Code FROM BarTable)

FooTable 只有 2 列:ID 和 Code(具有唯一约束的列)。

但是在 BarTable.Code 上,可能有一些重复的值我需要处理并将它们适合新的约束(可能是:Code = Code + 1 或其他)。

关于如何做到这一点的任何想法?

我正在使用 MS SQL Server 2008 R2。

提前谢谢你。

【问题讨论】:

    标签: sql-server sql-server-2008 insert constraints unique-constraint


    【解决方案1】:

    您可以使用MERGE 命令并在代码匹配时插入不同的记录。

    这是一个基于您的场景的示例:

    MERGE FooTable AS T
    USING BarTable AS S
    ON (T.Code = S.Code) 
    WHEN NOT MATCHED BY TARGET 
        THEN INSERT(Code) VALUES(S.Code)
    WHEN MATCHED 
        THEN INSERT(Code) VALUES(S.Code+1)
    

    【讨论】:

      【解决方案2】:

      您可以使用Not Exists

      INSERT INTO FooTable VALUES (SELECT distinct br.Code FROM BarTable br where NOT EXISTS(SELECT * FROM FooTable bs where br.code=bs.code  ) )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        相关资源
        最近更新 更多