Create an auto-increment column in Oracle

Source: Internet
Author: User

Since Oracle was used in the project for the first time. Ah, I am ashamed to be troubled by the problem of an auto-increment column for a long time. This is easy to use without SQL Server. Oracle needs to use auto-incrementing SEQUENCE and trigger.

1. To CREATE a SEQUENCE, you must first have the create sequence or create any sequence permission.
For example:

Create sequence s_id increment by 1 start with 1 MAXVALUE 999999999;
Create sequence s_id NOMAXVALUE NOCYCLE
-- Increment by 1 -- add several
-- Start with 1 -- count from 1
-- NOMAXVALUE -- do not set the maximum value
-- NOCYCLE -- always accumulate without repeating
-- CACHE 10;

After the SEQUENCE is defined, you can use s_id.CURRVAL to obtain the current SEQUENCE value, and use s_id.NEXTVAL to obtain the added SEQUENCE value.
2. Create the before insert trigger for the table and use the SEQUENCE

Create or replace trigger myTrigger
Before insert on myTable
Referencing old as old_value new as new_value
For each row
Begin
New_value.userid = s_id.nextval;
End;

Of course, a trigger can also be called directly when data is inserted.

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.