无法在对象' dbo.Countries'中插入重复键。重复键值为(1)

时间:2014-11-15 22:47:43

标签: sql sql-server

我正在尝试将数据从一个表复制到另一个表,我收到错误无法在对象' dbo.Countries'中插入重复键。重复键值为(1)。我明白这意味着什么,但我如何删除它? 这是我的sql server查询:

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)

1 个答案:

答案 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)

既然你要插入一个Identity字段,我也会在插入数据后执行以下代码行

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

这会将身份值重新设置为下一个最高可用标识值,否则当Identity列尝试生成您已明确插入标识列的标识值时,可能会出现重复错误。