3.触发器实际应用
需求:使用序列,触发器来模拟mysql中自增效果
案例中的效果是通过序列和触发器来实现对user表中的id自增的效果
每次进行添加的时候,触发器都会从序列中取出一个序列id添加到user正在插入的这条数据中;
-
创建序列
1、建立表
1 create table user 2 (3 4 id number(6) not null, 5 6 name varchar2(30) not null primary key 7 8 )
2、建立序列SEQUENCE
代码如下:
create sequence user_seq increment by 1 start with 1 minvalue 1 maxvalue 9999999999999 nocache order;
2.创建自增的触发器
分析:创建一个基于该表的before insert 触发器,在触发器中使用刚创建的SEQUENCE。
代码如下:
1 create or replace trigger user_trigger 2 3 before insert on user 4 for each row 5 begin 6 select user_seq.nextval into:new.id from sys.dual ; 7 end; 8
3.测试效果
1 insert into itcastuser(name) values(‘aa‘); 2 commit; 3 4 insert into itcastuser(name) values(‘bb‘); 5 6 commit;
时间: 2024-12-28 16:15:10