在设计数据库的时候,Oracle中没有类似SQL Server中系统自动分配ID作为主键的功能,这时Oracle可以通过“序列”和“触发器”来实现ID自动增加的功能。

1.创建序列Sequence

create sequence seq_uid
  increment by 1   
  start with 1    
  nomaxvalue    
  nocycle   
  cache 10 ;

其中:"seq_uid"表示自定义的序列名称

   "start with 1"表示序列值从1开始;

   "increment by 1"表示序列每次增加的值为1

序列的使用方法:

select seq_uid.nextval ID from dual

这样就得到了序列的下一个值,将这个语句放在触发器中,就可以实现类似SQL Server中ID自增的功能。

 
2.创建触发器Trigger
create trigger tri_uid before insert on [tablename] for each row when (new.[columnname] is null)
begin
    select seq_uid.nextval into:new.[columnname] from dual;
end;

其中:"tri_uid"表示自定义的触发器名称;

   "seq_uid"表示要使用的序列名称

   "[columnname]"表示要实现自增的列;

   "[tablename]"表示要实现自增的列所在的数据表

 

 

原文地址:https://www.cnblogs.com/imdeveloper/p/10334215.html
转载请注明出处,谢谢!

 

相关文章:

  • 2022-01-05
  • 2021-12-04
  • 2022-12-23
  • 2021-11-01
  • 2022-02-03
  • 2021-08-13
  • 2021-06-09
  • 2022-01-14
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-13
  • 2022-12-23
  • 2022-02-21
  • 2022-12-23
  • 2021-11-27
相关资源
相似解决方案