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

后端 未结 1 1929
情书的邮戳
情书的邮戳 2021-01-27 12:43

I am confused for a while since the Document point out:

When you create a PRIMARY KEY constraint, a unique clustered index on the column or columns is a

相关标签:
1条回答
  • 2021-01-27 12:56

    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.

    0 讨论(0)
提交回复
热议问题