Specific steps for Oracle Auto-incremental ID implementation

Source: Internet
Author: User

Today we are going to discuss with you the implementation of Oracle Auto-incremental ID. I am not sure about this problem. The information we saw on the relevant website two days ago is quite good, I hope it will help you in this regard.

First, you must have a table!

 
 
  1. CREATE TABLE example(  
  2. ID Number(4) NOT NULL PRIMARY KEY,  
  3. NAME VARCHAR(25),  
  4. PHONE VARCHAR(10),  
  5. ADDRESS VARCHAR(50) );  

Then, you need a custom sequence

Create sequence emp_sequence

Increment by 1 -- add several

Start with 1 -- count from 1

NOMAXVALUE -- do not set the maximum value

NOCYCLE -- always accumulate without repeating

NOCACHE -- do not create a buffer

The above code completes the establishment of a sequence, named emp_sequence. The range is from 1 to infinitely large (the degree of infinity is determined by your machine ), nocycle decides not to loop. If you set the maximum value, you can use cycle to make seq reach the maximum and then loop. for nocache, by the way, if you provide the cache value, the system will automatically read the seq of your cache value.

In this way, the operation speed will be accelerated during repeated operations. However, if an unexpected situation occurs, such as when the machine or oracle is dead, the seq value retrieved next time will be inconsistent with the previous one. (If the connection is not coherent, we recommend using cache because time is money! Run the question !)

You only have tables and sequences. You also need a trigger to execute them! The Code is as follows:

Create trigger "TRIGGER name" BEFORE

 
 
  1. INSERT ON example FOR EACH ROW WHEN (new.id is null)  
  2. begin  
  3. select emp_sequence.nextval into: new.id from dual;  
  4. end;  

Close the work! Next, try to insert data!

 
 
  1. INSERT INTO example(Name,phone,address) Values('Cao','56498543','Heibei'); 

A Brief Introduction to oracle sequence (auto-increment field )--

In oracle, sequence is the so-called serial number, which is automatically increased every time it is obtained. It is generally used in places where the sequence numbers need to be sorted.

1. Create Sequence

You must first have the Create Sequence or Create AnySequence permissions,

 
 
  1. Create Sequence emp_sequence 

Increment by 1 -- add several

STARTWITH 1 -- count from 1

NOMAXVALUE -- do not set the maximum value

NOCYCLE -- always accumulate without repeating

CACHE10;

Once emp_sequence is defined, you can use CURRVAL, NEXTVAL

CURRVAL = returns the current sequence Value

NEXTVAL = increase the sequence value, and then return the sequence Value

For example:

 
 
  1. emp_sequence.CURRVAL  
  2. emp_sequence.NEXTVAL  

Where sequence can be used:

-SELECT statements that do not contain subqueries, snapshot, and VIEW

-The INSERT statement is in the subquery.

-In the VALUES of the INSERT statement

-UPDATE in SET

See the following example:

 
 
  1. INSERT INTO emp VALUES  
  2. (empseq.nextval,'LEWIS','CLERK',7902,SYSDATE,1200,NULL,20);  
  3. SELECT empseq.currval FROM DUAL;  

Note that:

The first value returned by NEXTVAL is the initial value. The subsequent NEXTVAL will automatically increase the value of your defined INCREMENTBY and then return the added value. CURRVAL always returns the value of the current SEQUENCE, but CURRVAL can be used only after the first NEXTVAL initialization; otherwise, an error will occur. NEXTVAL increases the SEQUENCE value once. Therefore, if you use multiple NEXTVAL values in the same statement, their values are different. Understand?

If the CACHE value is specified, ORACLE can place some sequence in the memory in advance, so that the access speed is faster. After the cache is obtained, oracle automatically retrieves another group to the cache. The cache may be skipped, for example, when the database suddenly fails to shut down and shutdownabort), the sequence in the cache will be lost. Therefore, nocache can be used when createsequence is used to prevent this situation.

2. Alter Sequence

You are either the owner of the sequence, or you have the alter anysequence permission to modify the sequence. you can alter all sequence parameters except start. if you want to change the start value, you must drop sequence and re-create.

Alter sequence example

 
 
  1. ALTER SEQUENCE emp_sequence  
  2. INCREMENT BY 10  
  3. MAXVALUE 10000  

CYCLE -- start from scratch after 10000

NOCACHE;

Initialization parameters that affect Sequence:

SEQUENCE_CACHE_ENTRIES = sets the number of sequence that can be simultaneously cached.

It's easy to Drop Sequence.

 
 
  1. DRO SEQUENCE order_seq; 

Auto-growth and triggers:

In Oracle Auto-increment ID, how does one implement a function similar to auto-increment ID?

We often use an ID automatically assigned by the system as our primary key when designing a database, but this feature is not available in ORACLE, we can automatically add IDS by taking the following features

1. First create sequence

 
 
  1. create sequence seq maxincrement by 1 

2. Usage

 
 
  1. select seqmax.nextval ID from dual 

You get an ID.

If you put this statement in the trigger, you can use Oracle Auto-increment ID to automatically add the same ID function as mssql!

Create a table

 
 
  1. CREATE TABLE "SPORTS"."LINEUP"("ID" NUMBER NOT NULL,  
  2. "TYPE" NUMBER(3) NOT NULL,  
  3. "BODY" VARCHAR2(100) NOT NULL,  
  4. "HITS" NUMBER(10) DEFAULT 0 NOT NULL,  
  5. PRIMARYKEY("ID"))  
  6. TABLESPACE "TS_SPORTS"  

Sequence Creation

 
 
  1. CREATE SEQUENCE "SPORTS"."SPORTS_LINEUP_ID_SEQ" INCREMENT BY 1  
  2. START WITH 1 MAXVALUE 1.0E28 MINVALUE 1 NOCYCLE  
  3. CACHE 50 NOORDER  

Create an automatic update trigger

 
 
  1. CREATE OR REPLACE TRIGGER "SPORTS"."SPORTS_LINEUP_ID_TRIGGER"  
  2. BEFORE INSERT ON "SPORTS"."LINEUP" FOR EACH ROW  
  3. DECLARE  
  4. next_id NUMBER;  
  5. BEGIN  
  6. --Get the next id number from the sequence  
  7. SELECT sports_lineup_id_seq.NEXTVAL INTO next_id FROM dual;  
  8. --Use the sequence number as the primarykey  
  9. --for there cord being inserted.  
  10. :new.id:=next_id;  
  11. END;  

Create a trigger to protect PRIMARYKEY

 
 
  1. CREATE OR REPLACE TRIGGER "SPORTS"."LINEUP_ID_UPDATE_TRIGGER"  
  2. BEFORE UPDATE OF "ID" ON "SPORTS"."LINEUP" FOR EACHROW  
  3. BEGIN  
  4. RAISE_APPLICATION_ERROR(-20000,  
  5. 'sports_lineup_id_update_trigger:Update sof the ID field'  
  6. ||'arenotallowed.');  
  7. END;  

Create a delete trigger

 
 
  1. create or replace trigger tr_bis_exc_req_del  
  2. before delete  
  3. on bis_exc_req  
  4. referencing old as old new as new  
  5. for each row  
  6. begin  
  7. if :old.check_status = '3' then  
  8. raise_application_error (-20001,'*****!');  
  9. return;  
  10. end if;  
  11. end;  
  12. /  

Create an update trigger

 
 
  1. create or replace trigger tr_bis_exc_req_upd  
  2. before update  
  3. on bis_exc_req  
  4. referencing old as old new as new  
  5. for each row  
  6. begin  
  7. if :old.check_status = '3' then  
  8. raise_application_error (-20001,'*******!');  
  9. return;  
  10. end if;  
  11. end;   

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.