oracle数据库,怎么给已有数据的表添加自增字段

时间:2022-05-31 03:06:00

场景:数据仓库,ODI为使用Oracle Incremental Update IKM,需要对一事实表增加主键。

思想:基于老表创建新表,添加自增字段(序列+触发器实现),把老数据导入新表,删除老表,修改新表名字为老表

[1] 假如有一测试表DEPT,我们要给DEPT表增加ID字段

CREATE TABLE DEPT AS SELECT * FROM SCOTT.DEPT

或者自己创建

DROP TABLE "DEPT";
CREATE TABLE "DEPT" (
"DEPTNO" NUMBER(2) NOT NULL ,
"DNAME" VARCHAR2(14 BYTE) NULL ,
"LOC" VARCHAR2(13 BYTE) NULL 
)
;
INSERT INTO "DEPT" VALUES ('10', 'ACCOUNTING', 'NEW YORK');
INSERT INTO "DEPT" VALUES ('20', 'RESEARCH', 'DALLAS');
INSERT INTO "DEPT" VALUES ('30', 'SALES', 'CHICAGO');
INSERT INTO "DEPT" VALUES ('40', 'OPERATIONS', 'BOSTON');

oracle数据库,怎么给已有数据的表添加自增字段

【2】创建一个新表DEPT1

方法1: 导出源表结构,增加一个字段ID

CREATE TABLE "DEPT1" (
"ID" NUMBER(2) PRIMARY KEY,
"DEPTNO" NUMBER(2) NOT NULL ,
"DNAME" VARCHAR2(14 BYTE) NULL ,
"LOC" VARCHAR2(13 BYTE) NULL 
)

方法2:

---只会复制表数据和表结构,不会有任何约束
CREATE TABLE DEPT1 AS SELECT * FROM DEPT WHERE 1<>1

--添加列
ALTER TABLE "DEPT1" ADD ID NUMBER
ALTER TABLE "DEPT1" ADD PRIMARY KEY ("ID");

【3】创建自增序列

DROP SEQUENCE SEQ_DEPT

CREATE SEQUENCE SEQ_DEPT INCREMENT BY 1 START WITH 1 MINVALUE 1 NOMAXVALUE NOCYCLE NOCACHE;

【4】触发器实现ID自增加

DROP TRIGGER TRG_BEFORE_INSERT_DEPT
CREATE TRIGGER TRG_BEFORE_INSERT_DEPT  BEFORE INSERT ON DEPT1 
FOR EACH ROW
BEGIN
    SELECT
        SEQ_DEPT.NEXTVAL INTO :NEW.ID
    FROM
        DUAL ;
    END ;

【5】老数据导入新表DEPT1

INSERT INTO DEPT1("DEPTNO", "DNAME", "LOC") SELECT * FROM DEPT

【6】删除旧表DEPT

DROP TABLE DEPT

【7】DEPT1改名为DEPT

RENAME DEPT1 TO DEPT
---或者
ALTER TABLE DEPT RENAME TO DEPT;

【8】触发器会自动更新为新表。

DROP TRIGGER TRG_BEFORE_INSERT_DEPT
CREATE TRIGGER TRG_BEFORE_INSERT_DEPT  BEFORE INSERT ON DEPT FOR EACH ROW
BEGIN
    SELECT
        SEQ_DEPT.NEXTVAL INTO :NEW.ID
    FROM
        DUAL ;
    END ;

最终结果:

oracle数据库,怎么给已有数据的表添加自增字段