Write for Us
Error Message:Msg 8151, Level 16, State 0, Line 1Both a PRIMARY KEY and UNIQUE constraint have been defined for column '%.*ls', table '%.*ls'. Only one is allowed.
Severity level:16.
Description:This error message appears when you try to create both a PRIMARY KEY and a UNIQUE constraint on the same set of columns in a single statement.
Consequences:The T-SQL statement can be parsed, but causes the error at runtime.
Resolution:Errors of the Severity Level 16 are generated by the user and are corrigible by the user. The statement cannot be executed this way. You cannot create both constraints in a single statement, but rather need to split them in to two separated statements.
Versions:All versions of SQL Server.
Example(s):USE tempdb;GOIF OBJECT_ID('tempdb..#t') > 0 DROP TABLE #tGO CREATE TABLE #t( id INT CONSTRAINT PK_t PRIMARY KEY CONSTRAINT UC_t_id UNIQUE)GO
Remarks:In the above example we try upon table creation to create both a PRIMARY KEY and a UNIQUE constraint on the column id of the table #t. This raises the error.
In order to successfully execute the statement, you need to split the constraint creation into two separated statemtents like this:
USE tempdb;GOIF OBJECT_ID('tempdb..#t') > 0 DROP TABLE #tGO CREATE TABLE #t( id INT CONSTRAINT PK_t PRIMARY KEY)GOALTER TABLE #t ADD CONSTRAINT UC_t_id UNIQUE(id)