2.oracle数据库自增主键
不同于mysql,oracle主键自增不能在建表时直接设置,其实也很简单
1.建表
CREATE TABLE test(id NUMBER NOT NULL,key1 VARCHAR2(40) NULL,key2 VARCHAR2(40) NULL);
2.设置主键
alter table test add constraint test_pk primary key (id);
3.新建序列test_id
这里如果表中已经有id为1的数据了,那下次插入会失败,但是再次插入就会成功。
create sequence test_id //序列名称为test_idminvalue 1 //最小值nomaxvalue //无最大值限制increment by 1 //从1开始自增start with 1 nocache;
4.新建触发器test_insertId
create or replace trigger test_insertId //设置触发器的名称before insert on test for each row //在插入test之前,改成你自己的表名即可
beginselect test_id.Nextval into:new.id from dual; //选择触发器,第3步新建的触发器end;