Oracle 序列、触发器 语法

 序列: 生成类似于 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 : 下一个值
      
           注意: currval 需要在调用nextval之后才能使用      
           
           永不回头,往下取数据, 无论发生异常, 回滚   

案例:

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

使用该序列:

select seq_test1.nextval from dual; -- 获取下一个值,会触发序列自增
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;
           
       触发器的分类:
           语句级触发器:   不管影响多少行, 都只会执行一次
         
           行级触发器:     影响多少行,就触发多少次
                  :old  代表旧的记录, 更新前的记录
                  :new  代表的是新的记录

 案例一:

--新员工入职之后(插入emp表后),输出一句话: 欢迎加入程序员行业
create or replace trigger tri_test1
after
insert
on emp
declare

begin
  dbms_output.put_line('欢迎加入程序员行业');
end;

案例二:

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

案例三:

-- 每当往 person 插入数据时,自动把序列中下一个值赋给ID
create or replace trigger tri_add_person_pid
before
insert
on person
for each row
declare

begin
  dbms_output.put_line(:new.pname);
  --给新记录 pid 赋值
  select seq_person_pid.nextval into :new.pid from dual;
end;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值