oracle中觸發器的講解

來源:互聯網
上載者:User

標籤:

  觸發器在資料庫裡以獨立的Object Storage Service,它與預存程序和函數不同的是,預存程序與函數需要使用者顯示調用才執行,而觸發器是由一個事件來啟動運行。即觸發器是當某個事件發生時自動地隱式運行。並且,觸發器不能接收參數。所以運行觸發器就叫觸發或點火(firing)。ORACLE事件指的是對資料庫的表進行的INSERT、UPDATE及DELETE操作或對視圖進行類似的操作。ORACLE將觸發器的功能擴充到了觸發ORACLE,如資料庫的啟動與關閉等。所以觸發器常用來完成由資料庫的完整性條件約束難以完成的複雜商務規則的約束,或用來監視對資料庫的各種操作,實現審計的功能。

 

create sequence seq_userInfo_usid start with 1001;
create or replace triggle tri_userInfo_usid --建立或替換觸發器tri_userInfo_usid
before insert on userInfo--在向userInfo表中添加 記錄之前的觸發
for each row--沒影響一行出發一次
begin--觸發之後執行下面的語句
select seq_userInfo_usid.nextval into :new.usid from dual;--:new新值 :old老值
end;

 

案列

 

--日誌 觸發器講解

--查看所有觸發器
select * from user_triggers;
--禁用觸發器
alert trigger tri_log_uname(觸發器名字) disable;
--啟用觸發器
alert trigger tri_log_uname(觸發器名字) enble;
--重新編譯
alert trigger tri_log_uname complie;
--禁用某個表上的觸發器
alert table <table_name> diable all triggers;
create table log(
uname varchar2(20),
action varchar2(10),
acttime date
);

--從U001開始,以遞增的形式對uname進行命名
create sequence seq_log_uname start with 1001;
create or replace trigger tri_log_uname
before insert on log
for each row
begin
select ‘U‘||substr(seq_log_uname.nextval,1) into :new.uname from dual;
end;

insert into log values(1,‘yc‘,sysdate);
select * from log;

create or replace trigger tri_log
after insert or update or delete on dept
for each row--for each 行級觸發,執行語句沒影響一行出發一次,預設是語句級觸發,沒執行一條語句觸發一次,無論該語句影響多少行,
begin
if inserting then
insert into log values(user,‘insert‘,sysdate);
elsif updating then
insert into log values(user,‘update‘,sysdate);
elsif deleting then
insert into log values(user,‘delete‘,sysdate);
end if;
end;

select * from dept;
insert into dept values(80,‘技術部‘,‘湖南衡陽‘);

select * from log;

--更改dept和emp中的deptno的值(涉及主外鍵)
create or replace trigger tri_dept
before update on dept
for each row
begin
update emp set deptno=:new.deptno where deptno=:old.deptno;
end;

update dept set deptno=88 where deptno=20;
select * from dual;
select * from dept;
select * from emp;


create or replace trigger tri_emp
before update of sal on emp --當修改emp表中的sal列在值時
for each row
when(new.sal<=old.sal)
begin
select 3000 into :new.sal from dual;
end;

select * from emp;
update emp set sal=4000 where empno=7369;


oracle中觸發器的講解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.