Oracle使用序列和触发器实现自增ID

需求:

        向表中插入记录时,使得某列能够自动插入ID,并且插入的ID是自增的。

       我们可以先创建一个序列,例如 GOODS_GOODS_ID,然后每次使用如下SQL语句即可完成该功能,

insert into Goods(GoodsID, name) values ( GOODS_GOODS_ID.nextval, '农夫烤鸡');

若我们希望如下方式的SQL操作也能插入ID时,则需要另外的解法:

insert into Goods(name) values ('农夫烤鸡');

实现:

       首先创建一个序列,然后为表创建一个触发器,当表插入一行时,将序列的nextval的值插入指定列中。

/*==============================================================*/
/* 自增序列, GOODS.GOODS_ID         GOODS_GOODS_ID.Nextval      */
/*==============================================================*/
create sequence GOODS_GOODS_ID
minvalue 1
maxvalue 99999999999999999999
start with 1
increment by 1
nocache;


/*==============================================================*/
/* 触发器, 实现插入数据时, Goods表的Goods_ID字段自增    */
/*==============================================================*/
create or replace trigger trigger_goods_insert
  before insert on GOODS  
  for each row  
declare
  -- local variable here
begin  
  -- Column "Goods_ID" uses sequence GOODS_GOODS_ID
  select GOODS_GOODS_ID.nextval into :new.Goods_ID from dual;
end trigger_goods_insert;   


参考:

http://blog.csdn.net/zhangjunfangkaixin/article/details/4084211

你可能感兴趣的:(oracle,sql,insert,each)