Change Primary Key

南楼画角 提交于 2019-11-30 06:35:27

问题


I have a table in Oracle which has following Schema:

City_ID  Name  State  Country  BuildTime  Time

When i declared the table my primary key was both City_ID and the BuildTime but now I want to change the primary key to three columns:

City_ID  BuildTime  Time

How can I change the primary key?


回答1:


Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:

ALTER TABLE city
DROP CONSTRAINT pk_city;

ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);

Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.




回答2:


You will need to drop and re-create the primary key like this:

alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

However, if there are other tables with foreign keys that reference this primary key, then you will need to drop those first, do the above, and then re-create the foreign keys with the new column list.

An alternative syntax to drop the existing primary key (e.g. if you don't know the constraint name):

alter table my_table drop primary key;


来源:https://stackoverflow.com/questions/2310561/change-primary-key

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