Why does violation of PRIMARY KEY constraint return error code 2627 not 2601 in SQL Server?

帅比萌擦擦* 提交于 2019-12-02 09:18:46

A Primary Key, at least on SQL Server, is a type of Constraint. As a result when you create a Primary Key it is both a (unique) Index and a Constraint. Both error 2627 and 2601 have the same severity, so it appears that SQL Server will return the higher error code (as both a unique index and constraint were violated).

From testing, you'll only get the error 2601 is the column has a unique index that is violated, but does not have a constraint. Most likely, therefore, you'll see this on a conditional unique index.

Take the below examples:

USE Sandbox;
GO
--First sample table with primary key (Clustered)
CREATE TABLE dbo.TestTable1 (ID int PRIMARY KEY);
GO
--inserts fine
INSERT INTO dbo.TestTable1
VALUES(1);
GO
--Errors with code 2627
INSERT INTO dbo.TestTable1
VALUES(1);
GO
--Create second sample table, with unique Constraint
CREATE TABLE dbo.TestTable2(ID int,
                            CONSTRAINT U_ID UNIQUE(ID));
GO
--Inserts fine
INSERT INTO dbo.TestTable2
VALUES(1);
GO
--Errors with code 2627
INSERT INTO dbo.TestTable2
VALUES(1);
GO
--Create third sample table
CREATE TABLE dbo.TestTable3(ID int);
--Create unique index, without Constraint
CREATE UNIQUE INDEX ID_UX ON dbo.TestTable3(ID);
GO
--Inserts fine
INSERT INTO dbo.TestTable3
VALUES(1);
GO
--Errors with code 2601
INSERT INTO dbo.TestTable3
VALUES(1);
GO
--Clean up
DROP TABLE dbo.TestTable1
DROP TABLE dbo.TestTable2
DROP TABLE dbo.TestTable3

Note that only the last insert fails with error 2601; the other 2 fail with 2627.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!