I have a table with primary key in my MS SQL Server 2005 table. I would like to disable it. Now i get error:
Violation of PRIMARY KEY constraint 'PK_Name'. Cannot insert duplicate key in object 'dbo.Table'.
I would like this error not to occur and to work with PRIMARY KEY like with normal column without constraint and than restore this constraint after doing my changes to it. How to disable this constraint?
Query I want to execute while PRIMARY KEY constraint is disable is complex and changes values in primary key column. In some points of this query it hits the situation when I have duplicate values in primary key column. But at the end of my query I have all values unique.
I do not know much about this constraint because i'm not a designer of this table. I have it's name, but I don't now if it's clustered and so on (what is config of this column).
You can disable a primary key using the ALTER TABLE statement in SQL Server (Transact-SQL).
ALTER INDEX statement is used to disable a primary key in SQL Server database. Syntax: ALTER INDEX constraint_name ON table_name.
To delete a primary key constraint using Object ExplorerIn Object Explorer, expand the table that contains the primary key and then expand Keys. Right-click the key and select Delete. In the Delete Object dialog box, verify the correct key is specified and select OK.
We can remove PRIMARY KEY constraint from a column of an existing table by using DROP keyword along with ALTER TABLE statement.
ALTER TABLE mytable DROP CONSTRAINT PK_Name
To reenable it:
ALTER TABLE mytable ADD CONSTRAINT PK_Name PRIMARY KEY /* CLUSTERED */ (pk_column)
Uncomment CLUSTERED
if you want your PRIMARY KEY
to be clustered (i. e. the table rows themselves are being ordered)
To figure out if the PRIMARY KEY
is clustered on not, issue:
EXEC sp_help 'mytable'
and look in the 6th
resultset returned.
Relational tables without primary keys are a very bad thing. Each row has to be unique in some way. If none of the candidate keys are designated as primary, the whole row has to be unique.
I'm not sure why you have to drop a primary key constraint, but I would consider doing that without replacing it with one of the other candidate keys is a red flag that should be investigated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With