How to migrate from a composite primary key to a single attribute key in SQL?

泪湿孤枕 提交于 2019-12-11 03:40:40

问题


I would like to migrate a table that uses a composite primary key to a unique primary key.

My table is as follow:

  CREATE TABLE REGM 
  ( 
    LNG_CD VARCHAR2(2 BYTE) NOT NULL ENABLE, 
    REG_NRI NUMBER(10,0) NOT NULL ENABLE, 
    ...      
     CONSTRAINT PK_REGM PRIMARY KEY (LNG_CD, REG_NRI) ENABLE, 
  ); 

The table REGM uses LNG_CD and REG_NRI as a composite primary key. I would like to uses a primary key name REGM_PK instead, but still uses LNG_CD and REG_NRI as foreign key.

So far, this is my approach:

1 - Drop the contraint

ALTER TABLE REGM DROP CONSTRAINT PK_REGM;

2 - Add the primary key column

ALTER TABLE REGM ADD REGM_PK NUMBER(19,0);

3 - Create the sequence

CREATE SEQUENCE REGM_SEQ  MINVALUE 1 MAXVALUE 999999999999999999999999999 INCREMENT BY 1 START WITH 2 CACHE 20 NOORDER  NOCYCLE ;

4 - Fill the column with the sequence

5 - Make the REGM_PK column not null

6 - Create the primary key constraint

So far, I'm blocked at step #4

I know that I could also do a create/copy date/delete table. But I would prefer to do it in a SQL way.


回答1:


Step 4:

UPDATE  regm
SET     regm_pk = REGM_SEQ.nextval


来源:https://stackoverflow.com/questions/4145413/how-to-migrate-from-a-composite-primary-key-to-a-single-attribute-key-in-sql

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