2014-11-15 99 views
1

我想將數據從一個表複製到另一個,我得到的錯誤無法在對象'dbo.Countries'中插入重複鍵。重複的鍵值是(1)。我明白這意味着什麼,但我該如何刪除它?
這是我的SQL Server查詢:無法在對象'dbo.Countries'中插入重複鍵。重複的鍵值是(1)

SET IDENTITY_INSERT [dbo].[countries] ON 
    ----Create TestTable 
    CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100)) 
    ----INSERT INTO TestTable using SELECT 
    INSERT INTO [dbo].[Countries] (countryID, countryName) 
    SELECT countryId, countryName 
    FROM [dbo].[Sheet1] 
    ----Verify that Data in TestTable 
    SELECT countryID, countryName 
    FROM [dbo].[Countries] 
    ----Clean Up Database 
    DROP TABLE TestTable 
    SET IDENTITY_INSERT [dbo].[countries] OFF 

的錯誤信息是:

Msg 2627, Level 14, State 1, Line 6 
Violation of PRIMARY KEY constraint 'PK_dbo.Countries'. Cannot insert duplicate key in object 'dbo.Countries'. The duplicate key value is (1). 
The statement has been terminated. 

(26 row(s) affected) 
+0

源表怎麼可能有一個重複的ID開始? –

+0

單獨運行選擇並查看重複是否存在。 –

回答

1

嘗試......

INSERT INTO [dbo].[Countries] (countryID, countryName) 
SELECT countryId, countryName 
FROM [dbo].Sheet1 
WHERE NOT EXISTS (SELECT 1 
        FROM [dbo].[Countries] 
        WHERE Sheet1.countryId = [Countries].countryID) 

而且因爲要插入的標識字段我一旦完成插入數據,還將執行以下代碼行

DBCC CHECKIDENT ('[dbo].[Countries]', RESEED, 0) 
DBCC CHECKIDENT ('[dbo].[Countries]', RESEED) 
GO 

這會將標識值變爲次最高可用標識值,否則當標識列試圖生成已經顯式插入標識列的標識值時,您可能會得到重複的錯誤。

+0

我在Sheet1.countryId下得到一個紅色下劃線 –

+0

紅色下劃線並不一定意味着它會出錯,這可能是因爲你的本地緩存需要刷新。執行該語句並查看是否引發錯誤。 –

+0

我得到消息4104,級別16,狀態1,行14 無法綁定多部分標識符「Sheet1.countryId」。 –

相關問題