首页 > 代码库 > oracle中利用trigger,sequence自动生成ID

oracle中利用trigger,sequence自动生成ID

http://zhanghong.iteye.com/blog/865937

 

1. 首先创建数据库表

 

SQL> create table customer(

  2  id number(8) not null primary key,

  3  name varchar2(20),

  4  age number(3),

  5  gender varchar2(8)

  6  );

 

2. 创建Sequence:

create sequence customer_SEQUENCE start with 6 increment by 1

 

3.创建Trigger:

 

create or replace trigger customer_trgger 

         before insert or update on customer

         for each row

begin

         select customer_SEQUENCE.nextval into :NEW.userID from dual;

end;

 

 

在插入数据的时候就不用提供id了。

 

 

SQL> insert into customer(name,age,gender) values(‘abc‘,33,‘male‘);

 

1 row created.