Oracle primary key auto-Increment

Source: Internet
Author: User

Set the primary key and auto-increment the primary key in the Oracle table. Because Oracle cannot directly set the auto-increment number, you can only write sequence and add a trigger on your own;

After searching for a while on the network, I found that all of them were forwarded by blog posts. I wrote it according to their steps, but there was a problem. It was estimated that my own capabilities were limited. Many Masters did not dare to compliment me, I wrote it myself. The following is the step, only the auto-Increment Function of the Oracle primary key. The ORACLE trigger is very deep. I haven't sunk it yet. Please let me know at a high level ......

First create a table: Dept

Create Table dept (deptno number (10), deptname
Varchar2 (20), deptdescript varchar2 (20 ))

In this dept, deptno is the primary key;

The sequence is created below;

Create sequence dept_sequence
Increment by 1 start with 1 nomaxvalue nocycle Cache 10;

The following is a trigger. when data is inserted into a table, auto-increment of the primary key is triggered;
Create or replace trigger dept_trigger
Before insert on dept for each row
Begin select dept_sequence.nextval
Into: New. deptno from dual; end;

The sequence of my own table is marked with the color above, and the name of the trigger added by myself; it is not difficult to understand it;

Add the primary and foreign key references of the two tables: deptno is the primary key in Dept, and depment is the foreign key in EMP.

Alter table emp add constraint fr_key foreign key (depment)
References dept (deptno );

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.