加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

替代触发器的使用

(2010-11-03 22:00:50)
标签:

it

分类: oralce

当需要针对视图创建触发器来处理业务逻辑,或数据流程时, 可以用替代触发器来实现对视图相关表的操作.

SQL> create table stu(
    stuid int primary key,
    stuname varchar(10));

表已创建。

SQL> create table score(
    stuid int references stu(stuid),
    cid int,
    grade int);

表已创建。

SQL> create view v_stuscore
       as select stuid,stuname,cid,grade from stu natural join score;

视图已建立。
    create or replace trigger trig_view
       instead of insert or delete on v_stuscore
    for each row
    begin
       if inserting then
               insert into stu values(:new.stuid,:new.stuname);
               insert into score values(:new.stuid,:new.cid,:new.grade);
       elsif deleting then
               delete from stu where stuid = :old.stuid;
10              delete from score where stuid = :old.stuid;
11      end if;
12* end;
SQL> /

触发器已创建

 

 

SQL> create table user_info ( id number,name varchar2(200));
  Table created.
  SQL> insert into user_info values(1,'DINYA');
  1 row created.
  SQL> commit;
  Commit complete.
  SQL> create table skill( id number,skill varchar2(300),user_id number);
  Table created.
  SQL> insert into skill values(1,'打字',1);
  1 row created.
  SQL> commit;
  Commit complete.
  SQL> create or replace view user_skills as select a.id ,a.name,b.skill from user_info a,skill b wher
  e a.id=b.user_id;
  View created.
  SQL> select * from user_skills;
   ID NAME SKILL
  --------------- -------------------------------- -----------------------------------------------
   1 DINYA 打字
  
  SQL> update user_skills t set t.skill='上网' ;
  update user_skills t set t.skill='上网'
   *
  ERROR at line 1:
  ORA-01779: cannot modify a column which maps to a non key-preserved table
  
  SQL> create or replace trigger user_skills_update
  2 instead of update on user_skills
  3 for each row
  4 begin
  5 update skill set skill=:new.skill where user_id=:old.id;
  6 end ;
  7 /
  Trigger created.
  SQL> update user_skills t set t.skill='上网' where t.id=1;
  1 row updated.
  SQL> commit;
  Commit complete.
  SQL> select * from skill;
   ID SKILL USER_ID
  ----------------- --------------------- ---------------------------------------------------------
   1 上网 1

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有