微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Oracle使用sequence(序列)+tirgger(触发器)实现auto_increment(主键自增)

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编译不通过导致的,检查一下你是否存在语法错误,少了分号,括号,或者用错函数都会导致编译不过。

原文地址:https://www.jb51.cc/oracle/210714.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐