Oracle触发器
–今天我们根据学到的东西实现一个id列自动增长的触发器
–首先我们需要建个表,主键id,name不为空
create table student(
id number primary key,
name varchar2(50) not null
)
–查一下看看
select * from student
–要实现id列自动增长,我们需要一个序列来生成连续的整数数据对象,2020年,我们就从2020开始
create sequence seq_student_id
start with 2020 --从2020开始
increment by 1 --步长,默认升序为1,降序-1
nomaxvalue --最大值最小值
nocycle --达到最大值,最小值时,不重新开始,默认就是nocycle
cache 10; --使用cache时,序列会根据设定的规则生成一组序列号。保留在内存中,当使用下一个序列号时,速度更快些,oracle默认生成20个
–接下来,我们创建触发器,插入name时,自动插入id
create or replace trigger idsun_tri --创建触发器
before --触发器 数据操作之前 执行,还是 触发器 数据操作之后 执行
insert --触发 触发器 数据操作的 类型
on student --on 表名
for each row --行级触发器的关键字
declare --语句块
v_id number;
begin
select seq_student_id.NEXTVAL into v_id from dual;
:new.id:=v_id; --如果上面的数据操作类型是insert,:new表示将要插入的数据,使用:new.列名来调用,如果是update,:old表示更新前该行的值,:new表示更新后该行的值,如果是delete,:old表示删除前该行的值
end;
–插入两条数据试试
insert into student(name) values('SMITH');
insert into student(name) values('STIVEN');
select * from student;
–接下来再创建一个触发器,当插入的姓名是S开头时,抛出异常
create or replace trigger sname_tri
before
insert
on student
for each ROW
declare
goerror exception;
begin
if :new.name like 'S%' then
RAISE goerror;
end if;
end; --如果添加了EXCEPTION异常处理模块,就可以正常插入了。
–插入一个语句试一下
insert into student(name) values('SCRAY');
发现报错,抛出异常