Method for creating an auto-increment field in Oracle

Source: Internet
Author: User

In Oracle databases, Oracle Auto-increment fields are not supported, but can be implemented through triggers and sequence.

Assume that the [Table test] keyword segment is id and a sequence is created. The code is:

[Html]
  1. Create sequence seq_test
  2. Minvalue 1 -- Minimum value
  3. Maxvalue 99999999999 -- maximum value
  4. Start with 1 -- count from 1
  5. Increment by 1 -- add several
  6. Nocache -- no cache
  7. Order;

The code for creating a trigger is:

[Html]
  1. Create or replace trigger tri_test
  2. Before insert on test
  3. For each row
  4. Declare
  5. Nextid number;
  6. Begin
  7. IF: new. id is null or: New. id=0THEN
  8. Select seq_test.nextval
  9. Into nextid
  10. From sys. dual;
  11. : New. id:=Nextid;
  12. End if;
  13. End tri_test;

Keywords:

: NEW and: OLD use methods and meanings. new only appears in insert and update, and old only appears in update and delete. New indicates the row data to be inserted during insert, new indicates the new data to be replaced during update, and old indicates the original row to be changed, old indicates the data to be deleted.

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.