Change Primary Key to Composite Key (Primary Key already exists)

淺唱寂寞╮ 提交于 2019-12-04 00:21:03

问题


I am trying to change the primary key of a table in my SQL database from the existing key to a composite key, which does not include the existing column. The following code is not working due to the following error messages:

DROP PRIMARY KEY:

Incorrect Syntax near PRIMARY. Expecting COLUMN, CONSTRAINT, ID, or QUOTED_ID

ADD PRIMARY KEY:

Incorrect Syntax near PRIMARY. Expecting ID

T-SQL code:

ALTER TABLE AgentIdentification 
DROP PRIMARY KEY Number, 
ADD PRIMARY KEY (AgentId, IdIndicator)

EDIT

I was able to accomplish this by using the following two query statements

ALTER TABLE AgentIdentification 
DROP CONSTRAINT [PK_AgentId_Id]
GO

ALTER TABLE AgentIdentification
ADD CONSTRAINT pk_PersonID PRIMARY KEY (AgentId, IdIndicator)

Instead of requesting that SQL "DROP PRIMARY KEY" I needed to tell it to "DROP CONSTRAINT", also separating these two actions into two queries helped.


回答1:


    /* For SQL Server/Oracle/MS ACCESS */
    ALTER TABLE  AgentIdentification 
    DROP CONSTRAINT PK_Table1_Col1


    /* For MySql */
    ALTER TABLE  AgentIdentification 
    DROP PRIMARY KEY

To Add primary key :

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Table1
ADD CONSTRAINT pk_PersonID PRIMARY KEY (AgentId, IdIndicator)


来源:https://stackoverflow.com/questions/12167689/change-primary-key-to-composite-key-primary-key-already-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!