Implementation of Oracle Auto-increment Data Types

Source: Internet
Author: User
Tags informix

Implementation of Oracle Auto-increment Data Types

 

Author: Zhang guiquan

 

If you often use databases such as INFORMIX and MySQL, you will find that the database system itself provides an "auto-incrementing data class", such as the serial variable type of Informix. You only need to define the field as the serial type in create table to automatically increase the variable value, which is very convenient to use. However, if you are using an Oracle database, you need to implement this mechanism on your own. In fact, it is easy to implement. You only need to create a sequence variable and a trigger based on the target database. Nothing else is special. You may even find that the Oracle mechanism is more flexible than Informix, because you can control the starting point and incremental size of auto-increment variables. For example, you can define an auto-increment mechanism that increases from 1 to 5 at a time (of course, this design generally has no value for use ). The following uses a simple student record table as an example to describe how to implement the Oracle Auto-increment mechanism.

 

(1) create a basic table structure:

----------------------------------------

Create Table student

(

ID number,

Name varchar2 (40 ),

Age number,

Sex varchar2 (1 ),

Address varcharacter 2 (128 ),

Hponenumber varchar2 (16 ),

Primary Key (ID)

);

 

(2) create a sequence variable, which is based on 1 and increases by 1 each time.

Create sequence student_seq start with 1 increment by 1;

 

(3) create a trigger

Create or replace trigger student_trigger

Before insert on student

For each row

Begin

Select student_seq.nextval into: New. ID from dual;

End;

/

 

(4) now the auto-increment mechanism has been established. As long as you insert a record into the student table, the ID value will increase by 1, where the auto-increment base point is 1.

 

 

 

 

 

Related Article

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.