Both a PRIMARY KEY and UNIQUE constraint have been defined for column ‘%.*ls’, table ‘%.*ls’. Only one is allowed.

Error Message:
Msg 8151, Level 16, State 0, Line 1
Both 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 can be fixed by the SQL Server 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;
GO
IF OBJECT_ID(‘tempdb..#t’) > 0
 DROP TABLE #t
GO
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;
GO
IF OBJECT_ID(‘tempdb..#t’) > 0
 DROP TABLE #t
GO
CREATE TABLE #t
(
 id INT
 CONSTRAINT PK_t PRIMARY KEY
)
GO
ALTER TABLE #t
 ADD CONSTRAINT UC_t_id UNIQUE(id)




Related Articles :

  • No Related Articles Found

No comments yet... Be the first to leave a reply!

Software Reviews | Book Reviews | FAQs | Tips | Articles | Performance Tuning | Audit | BI | Clustering | Developer | Reporting | DBA | ASP.NET Ado | Views tips | | Developer FAQs | Replication Tips | OS Tips | Misc Tips | Index Tuning Tips | Hints Tips | High Availability Tips | Hardware Tips | ETL Tips | Components Tips | Configuration Tips | App Dev Tips | OLAP Tips | Admin Tips | Software Reviews | Error | Clustering FAQs | Performance Tuning FAQs | DBA FAQs |