如何在Oracle 11g中创建自动增量?

时间:2016-04-17 09:56:13

标签: sql database oracle oracle11g

我想为Oracle 11g中的主键生成7 DIGIT标识符。主键长度必须为7位。

这是我的代码:

CREATE SEQUENCE sequence_staff
MINVALUE 1
START WITH 1
INCREMENT BY 1;

CREATE TABLE Staff (
    Staff_ID    INT PRIMARY KEY, --Autoincrement 7 digit --PK
    Surname     VARCHAR2(50) NOT NULL,
    Firstnames  VARCHAR2(50) NOT NULL,
    Phone       VARCHAR2(30) NOT NULL,  --D1
    Address     VARCHAR2(150) NOT NULL
);

目前主键是1(1位),而不是0000001(7位)。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您必须按如下方式修改序列:

CREATE SEQUENCE sequence_staff
MINVALUE 1000000
START WITH 1000000
INCREMENT BY 1 NOCACHE NOCYCLE;

此外,您必须始终使用 sequence_staff.nextval 插入新的staff_id列。看看它是如何工作的

select sequence_staff.nextval from dual; --repeated times.

在此处详细了解序列https://docs.oracle.com/cd/B28359_01/server.111/b28310/views002.htm

编辑:

是的,有可能。按照您创建的方式创建序列:

select to_char(sequence_staff.nextval,'FM0000000') from dual;

编辑2:

此链接值得信赖。 http://stackoverflow.com/questions/14561210/creating-a-sequence-for-a-varchar2-field-in-oracle

编辑3:如果您真的想在Oracle数据库中按照自己的方式进行结果,那么您必须:

1. alter table staff modify staff_id varchar(20);
2. CREATE SEQUENCE sequence_staff
MINVALUE 1
START WITH 1
INCREMENT BY 1 NOCACHE NOCYCLE;
3. insert into staff(Staff_id, surname,firstnames, phone,address) values(to_char(sequence_staff.nextval,'FM0000000'),'Wayne','Bruce','0000','Gotha‌​m'); 

Result

答案 1 :(得分:0)

CREATE TABLE staff 
    ( 
        id         NUMBER(7) NOT NULL, 
            surname    VARCHAR2(50) NOT NULL, 
                firstnames VARCHAR2(50) NOT NULL, 
                    phone      VARCHAR2(30) NOT NULL, 
                        address    VARCHAR2(150) NOT NULL 
  );



ALTER TABLE Staff ADD (
  CONSTRAINT staff_pk PRIMARY KEY (ID));

    CREATE SEQUENCE staff_seq START WITH 1;

触发器定义:

            CREATE OR REPLACE TRIGGER staff_bir 
                BEFORE INSERT ON Staff 
                    FOR EACH ROW

                        BEGIN
                            SELECT staff_seq.NEXTVAL
                                INTO   :new.id
                                    FROM   dual;
                                       END;