Oracle 序列、触发器 语法

桃扇骨 2022-03-26 07:41 355阅读 0赞

** 序列: 生成类似于 auto_increment 这种ID自动增长 1,2,3,4,5….
auto_increment 这个是mysql

语法:
create sequence 序列的名称
start with 从几开始
increment by 每次增长多少
maxvalue 最大值 | nomaxvalue
minvalue 最小值 | nominvalue
cycle | nocycle 是否循环 1,2,3,1,2,3
cache 缓存的数量3 | nocache 1,2,3,4,5,6

如何从序列获取值
currval : 当前值
nextval : 下一个值

  1. 注意: currval 需要在调用nextval之后才能使用
  2. 永不回头,往下取数据, 无论发生异常, 回滚 **

案例:

  1. --创建一个 1,3,5,7,9......30
  2. create sequence seq_test1
  3. start with 1
  4. increment by 2
  5. maxvalue 30
  6. cycle
  7. cache 10;

使用该序列:

  1. select seq_test1.nextval from dual; -- 获取下一个值,会触发序列自增
  2. select seq_test1.currval from dual; -- 获取当前值,不会触发序列自增

** 触发器: 当用户执行了 insert | update | delete 这些操作之后, 可以触发一系列其它的动作/业务逻辑
作用 :
在动作执行之前或者之后,触发业务处理逻辑
插入数据,做一些校验
语法:
create [or replace] trigger 触发器的名称
before | after
insert | update | delete
on 表名
[for each row]
declare
— 声明变量
begin
— 执行操作的逻辑
end;

  1. 触发器的分类:
  2. 语句级触发器: 不管影响多少行, 都只会执行一次
  3. 行级触发器: 影响多少行,就触发多少次
  4. :old 代表旧的记录, 更新前的记录
  5. :new 代表的是新的记录**

案例一:

  1. --新员工入职之后(插入emp表后),输出一句话: 欢迎加入程序员行业
  2. create or replace trigger tri_test1
  3. after
  4. insert
  5. on emp
  6. declare
  7. begin
  8. dbms_output.put_line('欢迎加入程序员行业');
  9. end;

案例二:

  1. --数据校验, 星期六老板不在, 不能办理新员工入职
  2. --在插入数据之前
  3. --判断当前日期是否是周六
  4. --如果是周六,就不能插入
  5. create or replace trigger tri_test2
  6. before
  7. insert
  8. on emp
  9. declare
  10. --声明变量
  11. vday varchar2(10);
  12. begin
  13. --查询当前
  14. select trim(to_char(sysdate,'day')) into vday from dual;
  15. --判断当前日期:
  16. if vday = 'saturday' then
  17. dbms_output.put_line('老板不在,不能办理入职');
  18. --抛出系统异常
  19. raise_application_error(-20001,'老板不在,不能办理入职');
  20. end if;
  21. end;

案例三:

  1. -- 每当往 person 插入数据时,自动把序列中下一个值赋给ID
  2. create or replace trigger tri_add_person_pid
  3. before
  4. insert
  5. on person
  6. for each row
  7. declare
  8. begin
  9. dbms_output.put_line(:new.pname);
  10. --给新记录 pid 赋值
  11. select seq_person_pid.nextval into :new.pid from dual;
  12. end;

发表评论

表情:
评论列表 (有 0 条评论,355人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Oracle序列触发器

    序列 和 触发器 序列 序列是Oracle数据库中特有的一个对象,用来生成一组等间隔的数值。 序列(Sequence)是用来生成连续的整数数据的对象。