您还未登录!|登录|注册|帮助CSDN首页资讯论坛博客下载搜索更多CTO俱乐部学生大本营培训充电移动开发软件研发云计算程序员ITeyeTUPchinayuan的专栏目录视图摘要视图订阅精创之作《雷神的微软平台安全宝典》诚邀译者移动业界领袖会议·上海·6.20CSDN博客频道“移动开发之我见”主题征文活动【分享季1】:网友推荐130个经典资源,分享再赠分!数据库触发器分类:数据库2011-03-31 18:00 2889人阅读评论(2) 收藏举报触发器Oracle 触发器:触发器是特定事件出现的时候,自动执行的代码块。
类似于存储过程,但是用户不能直接调用他们。
功能:1 、允许/ 限制对表的修改2 、自动生成派生列,比如自增字段3 、强制数据一致性4 、提供审计和日志记录5 、防止无效的事务处理6 、启用复杂的业务逻辑开始:create trigger biufer_employees_department_idbefore insert or updateof department_idon employeesreferencing old as old_valuenew as new_valuefor each rowwhen (new_value.department_id<>80 )begin:new_mission_pct :=0;end;/触发器的组成部分:1 、触发器名称2 、触发语句3 、触发器限制4 、触发操作1 、触发器名称create trigger biufer_employees_department_id命名习惯:biufer (before insert update for each row )employees 表名department_id 列名2 、触发语句比如:表或视图上的DML 语句;DDL 语句,数据库关闭或启动,startup shutdown 等等before insert or updateof department_idon employeesreferencing old as old_valuenew as new_valuefor each row说明:( 1 )、无论是否规定了department_id ,对employees 表进行insert 的时候( 2 )、对employees 表的department_id 列进行update 的时候3 、触发器限制when (new_value.department_id<>80 )限制不是必须的。
此例表示如果列department_id 不等于80 的时候,触发器就会执行。
其中的new_value 是代表跟新之后的值。
4 、触发操作是触发器的主体begin:new_mission_pct :=0;end;主体很简单,就是将更新后的commission_pct 列置为0触发:insert into employees(employee_id,last_name,first_name,hire_date,job_id,email,department_id,salary,commission_pct ) values( 12345,‟Chen‟,‟Donny‟, sysdate, 12, …donny@‟,60,10000,.25);select commission_pct from employees where employee_id=12345;触发器不会通知用户,便改变了用户的输入值。
触发器类型:1 、语句触发器2 、行触发器3 、INSTEAD OF 触发器4 、系统条件触发器5 、用户事件触发器1 、语句触发器是在表上或者某些情况下的视图上执行的特定语句或者语句组上的触发器。
能够与INSERT 、UPDA TE 、DELETE 或者组合上进行关联。
但是无论使用什么样的组合,各个语句触发器都只会针对指定语句激活一次。
比如,无论update 多少行,也只会调用一次update 语句触发器。
例子:需要对在表上进行DML 操作的用户进行安全检查,看是否具有合适的特权。
Create table foo(a number);Create trigger biud_fooBefore insert or update or deleteOn fooBeginIf user not in (…DONNY‟) thenRaise_application_error(-20001, …Y ou don‟t have access to modify this table.‟);End if;End;/即使SYS ,SYSTEM 用户也不能修改foo 表[ 试验]对修改表的时间、人物进行日志记录。
1 、建立试验表create table employees_copy as select *from hr.employees2 、建立日志表create table employees_log( who varchar2(30), when date);3 、在employees_copy 表上建立语句触发器,在触发器中填充employees_log 表。
Create or replace trigger biud_employee_copyBefore insert or update or deleteOn employees_copyBeginInsert into employees_log( Who,when) V alues( user, sysdate);End;/4 、测试update employees_copy set salary= salary*1.1;select *from employess_log;5 、确定是哪个语句起作用?即是INSERT/UPDA TE/DELETE 中的哪一个触发了触发器?可以在触发器中使用INSERTING / UPDA TING / DELETING 条件谓词,作判断:beginif inserting then-----elsif updating then-----elsif deleting then------end if;end;if updating(…COL1‟) or updating(…COL2‟) then------end if;[ 试验]1 、修改日志表alter table employees_log add (action varchar2(20));2 、修改触发器,以便记录语句类型。
Create or replace trigger biud_employee_copyBefore insert or update or deleteOn employees_copyDeclareL_action employees_log.action%type;Beginif inserting thenl_action:=‟Insert‟;elsif updating thenl_action:=‟Update‟;elsif deleting thenl_action:=‟Delete‟;elseraise_application_error(-20001,‟Y ou should never ever get this error.‟);Insert into employees_log( Who,action,when) V alues( user, l_action,sysdate); End;/3 、测试insert into employees_copy( employee_id, last_name, email, hire_date, job_id)values(12345,‟Chen‟,‟Donny@hotmail‟,sysdate,12);select *from employees_logupdate employees_copy set salary=50000 where employee_id = 12345;2 、行触发器是指为受到影响的各个行激活的触发器,定义与语句触发器类似,有以下两个例外:1 、定义语句中包含FOR EACH ROW 子句2 、在BEFORE ……FOR EACH ROW 触发器中,用户可以引用受到影响的行值。
比如:定义:create trigger biufer_employees_department_idbefore insert or updateof department_idon employees_copyreferencing old as old_valuenew as new_valuefor each rowwhen (new_value.department_id<>80 )begin:new_mission_pct :=0;end;/Referencing 子句:执行DML 语句之前的值的默认名称是:old , 之后的值是:newinsert 操作只有:newdelete 操作只有:oldupdate 操作两者都有referencing 子句只是将new 和old 重命名为new_value 和old_value ,目的是避免混淆。
比如操作一个名为new 的表时。
作用不很大。
[ 试验] :为主健生成自增序列号drop table foo;create table foo(id number, data varchar2(20));create sequence foo_seq;create or replace trigger bifer_foo_id_pkbefore insert on foofor each rowbeginselect foo_seq.nextval into :new.id from dual;end;/insert into foo(data) values(…donny‟);insert into foo values(5,‟Chen‟);select * from foo;3 、INSTEAD OF 触发器更新视图instead of 触发器,可以实现: 不执行导致trigger 触发的语句,而只执行触发器. INSTEAD OF triggers provide a transparent way of modifying views that cannot be modified directly through DML statements (INSERT, UPDA TE, and DELETE). These triggers are called INSTEAD OF triggers because, unlike other types of triggers, Oracle fires the trigger instead of executing the triggering statement. Y ou can write normal INSERT, UPDA TE, and DELETE statements against the view and the INSTEAD OF trigger is fired to update the underlying tables appropriately. INSTEAD OF triggers are activated for each row of the view that gets modified.Create or replace view company_phone_book asSelect first_name||‟, ‟||last_name name, email, phone_number,employee_id emp_idFrom hr.employees;尝试更新email 和nameupdate pany_phone_book set name=‟Chen1, Donny1‟ where emp_id=100create or replace trigger update_name_company_phone_bookINSTEAD OFUpdate on pany_phone_bookBeginUpdate hr.employeesSet employee_id=:new.emp_id,First_name=substr(:, instr(:,‟,‟)+2),last_name= substr(:,1,instr(:,‟,‟)-1),phone_number=:new.phone_number,email=:new.emailwhere employee_id=:old.emp_id;end;instead of trigger 是基于视图建立的, 不能建在表上, 为什么要建在视图上, 一般的视图如果其数据来源一个表并且包含该表的主键, 就可以对视图进行DML 操作. 另外一种情况是从多个表查询出来的. 这样我们就不能对视图进行操作了, 也就是只能查询.instead of trigger 可以解决建在多表上视图的更新操作.下面我们就来实例操作:a. 先建表, 简单点就三个分别是学生表, 课程表, 学生选课表CREA TE TABLE STUDENT(CODE V ARCHAR2(5),LNAME V ARCHAR2(200))CREA TE TABLE COURSE(CODE V ARCHAR2(5),CNAME V ARCHAR2(30))CREA TE TABLE ST_CR(STUDENT V ARCHAR2(5),COURSE V ARCHAR2(5),GRADE NUMBER)-- 表的约束ALTER TABLE STUDENT ADD CONSTRAINT STUDENT$PK PRIMARY KEY(CODE); ALTER TABLE COURSE ADD CONSTRAINT COURSE$PK PRIMARY KEY(CODE); ALTER TABLE ST_CR ADD CONSTRAINT ST_CR$PK PRIMARY KEY(STUDENT, COURSE);ALTER TABLE ST_CR ADD CONSTRAINT ST_CR$FK$STUDENT FOREIGN KEY(STUDENT) REFERENCES STUDENT(CODE);ALTER TABLE ST_CR ADD CONSTRAINT ST_CR$FK$COURSE FOREIGN KEY(COURSE) REFERENCES COURSE(CODE);b. 基于这三个表的视图CREA TE OR REPLACE VIEW STUDENT_STA TUS ASSELECT S.CODE S_CODE, S.LNAME STUDENT, C.CODE C_CODE, AME COURSE, SC.GRADE GRADEFROM STUDENT S, COURSE C, ST_CR SCWHERE S.CODE = SC.STUDENTAND C.CODE = SC.COURSEc. 基于视图的触发器CREA TE OR REPLACE TRIGGER TRI_STCR INSTEAD OF INSERT ON STUDENT_STA TUSFOR EACH ROWDECLAREW_ACTION V ARCHAR2(1);BEGINIF INSERTING THENW_ACTION := 'I';ELSERAISE PROGRAM_ERROR;END IF;INSERT INTO STUDENT(CODE, LNAME) V ALUES(:NEW.S_CODE,:NEW.STUDENT);INSERT INTO COURSE(CODE, CNAME) V ALUES(:NEW.C_CODE, :NEW.COURSE);INSERT INTO ST_CR(STUDENT, COURSE, GRADE)V ALUES(:NEW.S_CODE, :NEW.C_CODE, :NEW.GRADE);END;d. 对视图执行数据插入INSERT INTO STUDENT_STA TUS(S_CODE, STUDENT, C_CODE, COURSE, GRADE)V ALUES('001','Mike','EN','English',86);可以看到每个表各有一条数据已经插入.4 、系统事件触发器系统事件:数据库启动、关闭,服务器错误create trigger ad_startupafter startupon databasebegin-- do some stuffend;/5 、用户事件触发器用户事件:用户登陆、注销,CREA TE / ALTER / DROP / ANALYZE / AUDIT / GRANT / REVOKE / RENAME / TRUNCA TE / LOGOFF例子:记录删除对象1. 日志表create table droped_objects(object_name varchar2(30),object_type varchar2(30),dropped_on date);2 .触发器create or replace trigger log_drop_triggerbefore drop on donny.schemabegininsert into droped_objects values(ora_dict_obj_name, -- 与触发器相关的函数ora_dict_obj_type,sysdate);end;/3. 测试create table drop_me(a number);create view drop_me_view as select *from drop_me;drop view drop_me_view;drop table drop_me;select *from droped_objects禁用和启用触发器alter trigger <trigger_name> disable;alter trigger <trigger_name> enable;事务处理:在触发器中,不能使用commit / rollback, 因为ddl 语句具有隐式的commit ,所以也不允许使用视图:dba_triggersMS SQLServer 触发器:SQL Sever 2005 包含的3 个触发器对象:AFTER ,数据定义语言(DDL) 和INSTEAD-OF1.AFTER 触发器是存储程序,它发生于数据操作语句作用之后,例如删除语句等。