Sample Code for creating an auto-increment field in the Oracle database

Source: Internet
Author: User

Oracle DatabaseMediumCreate an auto-increment FieldThe method is what we will introduce in this article. We know that there is no Oracle Auto-incrementing field function in the Oracle database, but trigger and sequence are used) yes.

Assume that the [Table test] keyword segment is id. Next we will introduce the creation process:

Create a sequence with the code:

 
 
  1. Createsequenceseq_test
  2. Minvalue1 -- Minimum value
  3. Maxvalue99999999999 -- maximum value
  4. Startwith1 -- count from 1
  5. Incrementby1 -- add a few
  6. Nocache -- no cache
  7. Order;

The code for creating a trigger is:

 
 
  1. createorreplacetriggertri_test  
  2. beforeinsertontest  
  3. foreachrow  
  4. declare  
  5. nextidnumber;  
  6. begin  
  7. IF:new.idISNULLor:new.id=0THEN 
  8. selectseq_test.nextval  
  9. intonextid  
  10. fromsys.dual;  
  11. :new.id:=nextid;  
  12. endif;  
  13. endtri_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.

This article describes how to create an auto-increment field in an Oracle database. We hope this article will be useful to you!

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.