0

這裏我試圖從表列中將一些數據遷移到目標列有唯一約束的全新表。基本上我試圖:如何處理數據遷移腳本中的唯一約束違規?

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

FooTable只有2列:ID和代碼(具有唯一約束的列)。

但BarTable.Code,也許有一些重複的值,我需要對待和適應他們在新的約束(也許:Code = Code + 1或其他)。

關於如何做到這一點的任何想法?

我正在使用MS SQL Server 2008 R2。

預先感謝您。

回答

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) 
0

您可以使用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 )) 
+0

感謝你回答@legendinmaking – 2013-04-27 20:39:13

相關問題