Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set column as primary key if the table doesn't have a primary key

Tags:

tsql

I have a column in db which has 5 columns but no primary key. One of the columns is named myTable_id and is integer.

I want to check if the table has a primary key column. If it doesn't, then make myTable_id a primary key column and make it identity column. Is there a way to do this?

I tried with this:

ALTER TABLE Persons DROP CONSTRAINT pk_PersonID  ALTER TABLE Persons ADD PRIMARY KEY (P_Id) 

and I get syntax error in Management studio.

like image 551
petko_stankoski Avatar asked Feb 01 '13 13:02

petko_stankoski


People also ask

What if a table does not have primary key?

Every table can have (but does not have to have) a primary key. The column or columns defined as the primary key ensure uniqueness in the table; no two rows can have the same key. The primary key of one table may also help to identify records in other tables, and be part of the second table's primary key.

Can a column reference a non primary key?

If the foreign key refers to a non-primary unique key, you must specify the column names of the key explicitly. If the column names of the key are not specified explicitly, the default is to refer to the column names of the primary key of the parent table.

How do you make a column not a primary key?

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


1 Answers

This checks if primary key exists, if not it is created

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS  WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'Persons'  AND TABLE_SCHEMA ='dbo') BEGIN    ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id) END ELSE BEGIN    -- Key exists END 

fiddle: http://sqlfiddle.com/#!6/e165d/2

like image 175
Urban Björkman Avatar answered Nov 10 '22 13:11

Urban Björkman