序列,触发器等相关的使用

微软下的Sqlserver实现增长只要设定列identity

create table myTable(

id int identity(1,1) primary key not null,

name varchar(15)

);

MySql下实现自增长只要设定列auto_increment

create table myTable(

id int auto_increment primary key not null,

name varchar(15)

);

Oracle数据库有点不同,没有像MySql和Sqlserver数据库的那样具有一个自增长列类型,而是通过序列来实现唯一性和自增长性.

create table employee(
       PID number,
       PTitle varchar2(16),
       PContent varchar2(max)
       PublishDate date,
       IsShow number,
       constraint pk_employee primary key(PID)
       );

序列:

create sequence publish_autoinc
     minvalue 1
     maxvalue 9999999999999999999999999999
     start with 1
     increment by 1
     nocache;

一旦定义了publish_autoinc序列,就可以访问序列的curval和nextval属性。
•curval:返回序列的当前值
•nextval:先增加序列的值,然后返回序列值

insert into employee values(publish_autoinc.nextval, 'PTitle1','PContent1',sysdate,1);

使用触发器:

        
  create or replace trigger insert_publish_autoinc
     before insert  on publish
     for each row
          begin
               select publish_autoinc.nextval into :new.PID from dual;
          end insert_publish_autoinc;    
                 

这样每当对publish表进行Insert操作,都会自动将序列的下一个值插入到PID中,从而实现自增长.

 

 

 

 

END

 

posted on 2015-10-09 22:00  巴夫巴夫  阅读(199)  评论(0编辑  收藏  举报