--禁止工作人员在休息日改变雇员信息触发器
create or replace trigger tr_src_emp
before insert or update or delete on emp
begin
if to_char(sysdate,'DY','nls_date_langage=AMERICAN') in ('SAT','SUN') THEN
raise_application_error(-20001,'cant modify user information in weekend');
END IF;
END;
delete from emp where deptno=12;
update emp set deptno=100 where deptno=100;
insert into emp(empno,deptno,sal) values(12,12,14552);
drop trigger tr_src_emp;
--利用条件谓语
--禁止工作人员在休息日改变雇员信息触发器
create or replace trigger tr_src_emp1
before insert or update or delete on emp
begin
if to_char(sysdate,'DY') in('星期六','星期日') THEN
case
WHEN inserting then
raise_application_error(-200001,'fail to insert');
WHEN updating THEN
raise_application_error(-200001,'fail to update');
WHEN deleting THEN
raise_applicate_error(-20001,'fail to delete');
END CASE;
END IF;
END;
create table audit_table
(
name varchar(20),
upd int,
ins int,
del int,
starttime date,
endtiem date
);
alter table audit_table rename column endtiem to endtime;
--记录表emp的修改,删除,更新操作的次数.
create or replace trigger tr_src_emp2
after update or delete or insert on emp
DECLARE
v_temp number;
BEGIN
SELECT count(*) into v_temp from audit_table where name='EMP';
IF v_temp =0 THEN
Insert into audit_table values('EMP',0,0,0,sysdate,null);
END IF;
CASE
WHEN inserting THEN
Update audit_table set ins=ins+1,endtime=sysdate where name='EMP';
WHEN updating THEN
Update audit_table set upd=upd+1,endtime=sysdate where name='EMP';
WHEN deleting THEN
Update audit_table set del=del+1,endtime=sysdate where name='EMP';
END CASE;
END;
--行触发器
--before触发器
create or replace trigger tr_emp_sal
before update of sal on emp
for each row
begin
if :new.sal<:old.sal THEN
raise_application_error(-20010,'sal should not be less');
END IF;
END;
--建一个表用来存放sal修改信息
create table audit_emp_change
(
name varchar2(20),
oldsal number(6,2),
newsal number(6,2),
tdate date
);
insert into audit_emp_change(oldsal,newsal) values(11,11);
select * from audit_emp_change;
--after 触发器
Create or replace trigger tr_sal_sal
after update of sal on emp
for ench row
declare
v_temp int;
begin
select count(*) into v_temp form audit_emp_change where name=:old.ename;
IF v_temp=0 THEN
insert into audit_emp_change values(:old.ename,:old.sal,:new.sal,sysdate);
ELSE
update audit_emp_change set oldsal=:old.sal,newsal=:new.sal,tdate=sysdate where name=:old.ename;
end if;
end;
--限制行触发器
Create or replace trigger tr_sal_sal
after update of sal on emp
for each row
when(old.job='SALESMAN')
DECLARE
v_temp number;
select count(*) into v_temp from audit_emp_change where name=:old.enmae;
if v_temp=0 then
insert into audit_emp_change values(:old.enmae,:old.sal.:new.sal,sysdate);
ELSE
UPDATE audit_emp_change set oldsal=:old.sal,newsal=new.sal,time=sysdate where name=:old.ename;
end IF;
end;
--注意: 编写 DML 触发器的时,触发器代码不能从触发器所对应的基表中读取数据。