oracle 实现表中某个字段的自动增加(相当于有些数据库的自增列)

来源:互联网 发布:懒人听书软件 编辑:程序博客网 时间:2024/06/02 02:06

说明:sqlserver 中设置某个列的自动增加是非常容易的,只需要在列后面加上 auto_increment即可,但是oracle在使用sql语句创建表时时不支持这种自增的。

那么要实现自增列怎么办? 三步搞定


--1.创建表-----
CREATE TABLE users (
  id number(11) NOT NULL ,
  username varchar2(100) NOT NULL,
  user_password varchar2(100) NOT NULL,
  user_status integer DEFAULT NULL,
  register_time date DEFAULT NULL,
  PRIMARY KEY (id)
)
--2.创建序列-----
create sequence users_seq
increment by 1
start with 1
nomaxvalue
nocycle cache 10;


---3.创建触发器-----
create or replace trigger users_trigger
before insert on users
for each row
declare
 nextid number;
begin
if :new.id is null or :new.id=0 then
 select users_seq.nextval into nextid  from sys.dual;
        :new.id:=nextid;
 end if;
end users_trigger;


--4.测试----
insert into  users (username,user_password) values('admin0','111111');


select * from users;

0 0
原创粉丝点击