Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable primary key constraint programmatically?

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).

like image 886
Tom Smykowski Avatar asked Apr 10 '09 09:04

Tom Smykowski


People also ask

Is it possible to disable primary key constraint?

You can disable a primary key using the ALTER TABLE statement in SQL Server (Transact-SQL).

Can we disable primary key constraint in SQL Server?

ALTER INDEX statement is used to disable a primary key in SQL Server database. Syntax: ALTER INDEX constraint_name ON table_name.

How do I remove a primary constraint?

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.

How can the primary key constraint be removed from the table?

We can remove PRIMARY KEY constraint from a column of an existing table by using DROP keyword along with ALTER TABLE statement.


2 Answers

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.

like image 89
Quassnoi Avatar answered Nov 05 '22 02:11

Quassnoi


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.

like image 45
duffymo Avatar answered Nov 05 '22 02:11

duffymo