Oracle使用sequence(序列)+tirgger(触发器)实现auto_increment(
发布时间:2020-12-12 15:24:13 所属栏目:百科 来源:网络整理
导读:受mysql的影响,在oracle建表的时候差点就控制不住自己的麒麟臂打下auto_increment。不过Oracle提供了一套机制也可以实现自增主键,虽然稍微麻烦点也算是殊途同归。 数据准备-测试表: create table hello( hellokey varchar2(32),anotherkey varchar2(16),w
受mysql的影响,在oracle建表的时候差点就控制不住自己的麒麟臂打下auto_increment。不过Oracle提供了一套机制也可以实现自增主键,虽然稍微麻烦点也算是殊途同归。 数据准备-测试表: create table hello( hellokey varchar2(32),anotherkey varchar2(16),whatever varchar2(16),primary key(hellokey,anotherkey) ); 实现步骤: 首先创建序列,注意你的数据库用户必须拥有创建序列的权限。 create sequence testseq increment by 1 start with 1 maxvalue 3 --注意这里只是为了看循环的效果而把最大值设置为3,正常情况应该根据需要设置为比较大的值比如9999999 cycle cache 2; 上面的语句,创建了一个名为testseq的序列,其参数含义依次为: (这csdn真心是不会用。。。插表不能换行,强行插图) 接下来创建触发器 create or replace trigger my_trigger before insert on hello for each row declare tempkey hello.hellokey%type; --声明临时变量tempkey,hello.hellokey%type表示取hello表的hellokey的类型 begin select testseq.NEXTVAL into tempkey from dual; -- testseq.NEXTVAL 表示取序列testseq的下一个自增值 if :new.hellokey is null then -- :new表示要新插入的这一行 :new.hellokey := to_char(sysdate,'yyyymmdd') ||'-'|| tempkey; --如果要插入的行中hellokey列为空,则生成一个"系统日期-自增值"形式的key end if; end; 这个触发器会在我们每次插hello表时检查hellokey字段是否为空,若空就补充一个key值上去。
测试: 到这里为止,我们就完成了序列+触发器实现的主键自增,下面来测试下。 insert all into hello(anotherkey,whatever) values('100','xxx') into hello(anotherkey,whatever) values('101',whatever) values('102',whatever) values('103',whatever) values('104','xxx') select 1 from dual; 查看hello表,可以看到:
最后,如果你创建好了触发器,在插值的时候报错oracle trigger xxx is invalid and failed re-validation,那是因为你写的trigger编译不通过导致的,检查一下你是否存在语法错误,少了分号,括号,或者用错函数都会导致编译不过。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |