想在项目中插入一个序列,对序列的概念以及用法有点模糊,通过查阅资料现在已经对在oracle中插入序列有了一定的了解:
创建一个序列:
create sequence SEQ_FileInfo_GW
minvalue 100000000
maxvalue 299999999
start with 100000000
increment by 1;
当向表中插入数据时,SQL语句写法如下:
INSERT
INTO my_table(id,...) values(seq.NEXTVAL,...)
触发器应用场景:
1、强化约束
2、跟踪变化
3、级联运行
4、存储过程的调用
触发器分类:
1、DML触发器
2、INSTEAD OF触发器
3、系统触发器
--demo
--创建一个语句级触发器,不允许用户在“星期日”使用emp表。
CREATE OR REPLACE
TRIGGER not_sunday
BEFORE INSERT OR
UPDATE OR DELETE ON emp
BEGIN
IF rtrim(to_char(SYSDATE,'day'))='SUNDAY'
THEN
raise_application_error(-20333,'Sorry!Not
on Sundays');
END IF;
END;
--demo
--创建一个行级触发器,将从emp表中删除的记录输入到ret_emp表中
--step1
CREATE TABLE ret_emp
AS SELECT * FROM emp;
--step1
CREATE OR REPLACE
TRIGGER emp_retire
BEFORE DELETE ON emp
FOR EACH ROW
BEGIN
INSERT INTO ret_emp VALUES
(:OLD.empno,:OLD.ename,:OLD.job,:OLD.mgr,:OLD.hiredate,:OLD.sal,:OLD.comm,:OLD.deptno);
END;
--demo
--创建一个行级触发器,停止用户删除'president'的记录。
CREATE OR REPLACE
TRIGGER not_president
BEFORE DELETE ON emp
FOR EACH ROW
WHEN
(old.job='PRESIDENT')
BEGIN
raise_application_error(-20444,'CANNOT DELETE
PRESIDENTS RECORD');
END;
--demo
--创建instead of触发器,通过视图添加数据。
--step1
create or replace
view v_deptemp
as
select dept.deptno,dept.dname,
emp.empno,emp.ename
from dept,emp
where dept.deptno = emp.deptno;
--step2
insert into
v_deptemp values(90,'dept',9001,'emp');
--step3
create or replace
trigger tr_i_deptemp
instead of insert on
v_deptemp
for each row
declare
v_num number;
begin
select count(*) into v_num
from dept where deptno = :new.deptno;
if v_num = 0 then
insert into dept(deptno,dname)
values(:new.deptno,:new.dname);
end if;
select count(*) into v_num
from emp where empno = :new.empno;
if v_num = 0 then
insert into emp(empno,ename)
values(:new.empno,:new.ename);
end if;
end;
--step4
insert into
v_deptemp values(90,'dept',9001,'emp');
--demo
--创建DDL触发器
--step1
create table tmp
( tid number,
tdesc varchar2(20)
);
--step2
create or replace
trigger ddlschema
after create or drop
or alter on schema
begin
insert into tmp values(1,'create');
end;
--demo
--创建DDL触发器
--step1
grant administer
database trigger to scott;
--step2
create or replace
trigger loguser
after logon on
schema
begin
insert into tmp values(1,'user log');
end;
--step3
create or replace
trigger logalluser
after logon on
database
begin
insert into scott.tmp values(2,'user all
log');
end;
-- 学海无涯