Implementing a self-increment ID in Oracle

Source: Internet
Author: User

In some databases (for example, MySQL), implement the self-increment ID as long as you specify it when you build the table,

But in Oracle, with sequence to implement the self-increment ID,

There are several ways to use the self-increment ID:

1. Use sequence's nextval directly in the INSERT statement.

2. Set default for the field when building the table, which I haven't tested yet.

3. Use a trigger, about the way the trigger, from someone else that got an example, for the moment to paste here as a memo. I think that if the default mode is available, it will be simpler than using a trigger.

Here is the code for how the trigger is Related:

CREATE TABLE STUDENT
(
ID INT not NULL,
NAME VARCHAR2 (4000) is not NULL,
PRIMARY KEY (ID)
)
Tablespace MYDB;

--Create a self-increment ID named: Table name _ Field name _seq
CREATE SEQUENCE student_id_seq MINVALUE 1 nomaxvalue INCREMENT by 1 START with 1 NOCACHE;


--Create a trigger for the insert operation without having to write nextval in the SQL statement, name is table name _INS_TRG
CREATE OR REPLACE TRIGGER student_ins_trg before INSERT on STUDENT for each ROW if (New.id is NULL)
BEGIN
SELECT Student_id_seq. Nextval INTO:NEW.ID from DUAL;
END;

Not to be continued

Implementing a self-increment ID in Oracle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.