oracle设置触发器让id自动增递

-- 删除数据库已有的student表
drop table student;
-- 创建student表 并设置主键
create TABLE student(
 tid number primary key,
 tname varchar2(20)
);
-- 如果没加主键 可修改位主键
alter table student add CONSTRAINT sid_pk PRIMARY key(tid);

-- 删除已有的序列
drop SEQUENCE emp_tid;

-- 创建序列
create SEQUENCE emp_tid
MINVALUE 1 --初始最小值
maxvalue 999999999  --最大值
start WITH 1
increment by 1
cache 20;

-- 创建触发器 实现自动增递
--格式
--create or replace trigger "触发器名"
--before insert on 表名 
--referencing old as old new as new for each row
--DECLARE
--begin
-- select 序列名.nextval into:new.要增递的主键 from dual;
--end;
--insert into student(tname) values(2);--测试是否可行

--例子
create or replace trigger "msg_tri"
before insert on student 
referencing old as old new as new for each row
DECLARE
begin
 select emp_tid.nextval into:new.tid from dual;
end;
insert into student(tname) values(2);




猜你喜欢

转载自blog.csdn.net/qq_39313596/article/details/80549593