Add primary key to existing table

后端 未结 10 1556
生来不讨喜
生来不讨喜 2020-12-07 11:40

I have an existing table called Persion. In this table I have 5 columns:

  • persionId
  • Pname
  • PMid
  • Pdescription
  • Pa
10条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 12:14

    There is already an primary key in your table. You can't just add primary key,otherwise will cause error. Because there is one primary key for sql table.

    First, you have to drop your old primary key.

    MySQL:

    ALTER TABLE Persion
    DROP PRIMARY KEY;
    

    SQL Server / Oracle / MS Access:

    ALTER TABLE Persion
    DROP CONSTRAINT 'constraint name';
    

    You have to find the constraint name in your table. If you had given constraint name when you created table,you can easily use the constraint name(ex:PK_Persion).

    Second,Add primary key.

    MySQL / SQL Server / Oracle / MS Access:

    ALTER TABLE Persion ADD PRIMARY KEY (PersionId,Pname,PMID);
    

    or the better one below

    ALTER TABLE Persion ADD CONSTRAINT PK_Persion PRIMARY KEY (PersionId,Pname,PMID);
    

    This can set constraint name by developer. It's more easily to maintain the table.

    I got a little confuse when i have looked all answers. So I research some document to find every detail. Hope this answer can help other SQL beginner.

    Reference:https://www.w3schools.com/sql/sql_primarykey.asp

提交回复
热议问题