建立
dml語句行級觸發器。當對
emp表執行
insert, update, delete
操作時,它自動更新
dept_summary
表中的資料。由於在
pl/sql
塊中不能直接呼叫
ddl語句,所以,利用
oracle
內建包dbms_utility
中的exec_ddl_statement
過程,由它執行
ddl語句建立觸發器:
begin
dbms_output.put_line('
插入前');
disp_dept_summary();
dbms_utility.exec_ddl_statement(
'create or replace trigger trig2_update
after update of sal on emp
referencing old as old_emp new as new_emp
for each row
when (old_emp.sal != new_emp.sal)
begin
dbms_output.put_line(
''正在執行trig2_update 觸發器…
'');
dbms_output.put_line(
''sal 舊值:
''|| :old_emp.sal);
dbms_output.put_line(
''sal 新值:
''|| :new_emp.sal);
update dept_summary
set sal_sum=sal_sum + :new_emp.sal - :old_emp.sal
where deptno = :new_emp.deptno;
end;');
dbms_utility.exec_ddl_statement(
'create or replace trigger trig2_insert
after insert on emp
referencing new as new_emp
for each row
declare
i number;
begin
dbms_output.put_line(
''正在執行trig2_insert 觸發器…
'');
select count(*) into i
from dept_summary where deptno = :new_emp.deptno;
if i > 0 then
update dept_summary
set sal_sum=sal_sum+:new_emp.sal,
emp_count=emp_count+1
where deptno = :new_emp.deptno;
else
insert into dept_summary
values (:new_emp.deptno, :new_emp.sal, 1);
end if;
end;');
dbms_utility.exec_ddl_statement(
'create or replace trigger trig2_delete
after delete on emp
referencing old as old_emp
for each row
declare
i number;
begin
dbms_output.put_line(
''正在執行trig2_delete 觸發器…
'');
select emp_count into i
from dept_summary where deptno = :old_emp.deptno;
if i >1 then
update dept_summary
set sal_sum=sal_sum - :old_emp.sal,
emp_count=emp_count - 1
where deptno = :old_emp.deptno;
else
delete from dept_summary where deptno = :old_emp.deptno;
end if;
end;');
insert
into dept(deptno, dname, loc)
values(90, '
demo_dept
', '
none_loc
');insert
into emp(ename, deptno, empno, sal)
values(user,90,9999,3000);
insert
into emp(ename, deptno, empno, sal)
values(user,90,9998,2000);
dbms_output.put_line('
插入後');
disp_dept_summary();
update emp set sal = sal*
1.1where deptno=
90;
dbms_output.put_line('
修改後');
disp_dept_summary();
delete
from emp where deptno=
90;
delete
from dept where deptno=
90;
dbms_output.put_line('
刪除後');
disp_dept_summary();
dbms_utility.exec_ddl_statement('
drop trigger trig2_update
');dbms_utility.exec_ddl_statement('
drop trigger trig2_insert
');dbms_utility.exec_ddl_statement('
drop trigger trig2_delete
');exception
when others then
dbms_output.put_line(sqlcode||
'---
'||sqlerrm);
end;
SQL Server 建立觸發器(trigger)
觸發器簡介 觸發器是一種特殊的儲存過程,它的執行不是由程式呼叫,也不是手動執行,而是由事件來觸發。觸發器是當對某乙個表進行操作。例如 update insert delete這些操作的時候,系統會自動呼叫執行該錶上對應的觸發器。觸發器分類 1 dml 資料操縱語言 data manipulation...
oracle資料庫觸發器使用 trigger
1.更新前觸發,不允許週日修改 create or replace trigger auth secure before insert or update or delete on tb emp begin if to char sysdate,dy 星期日 then end if end 2.自增...
ORACLE觸發器 行級觸發器
行級觸發器 本章介紹行級觸發器機制。大部分例子以insert出發器給出,行級觸發器可從insert update delete語句觸發。1 介紹 觸發器是儲存在資料庫已編譯的儲存過程,使用的語言是pl sql,用編寫儲存過程一樣的方式編寫和編譯觸發器。下面在sql plus會話中建立和示例乙個簡單的...