繁体   English   中英

PL-SQL 中的触发器

[英]Triggers in PL-SQL

我有两个表:

create table speciality(
major          varchar2(30),
total_credits  number,
total_students number);

create table students(
id              number(5) primary key,
first_name      varchar2(20),
last_name       varchar2(20),
major           varchar2(30),
current_credits number(3));

我想创建一个名为UpdateSpeciality的触发器,当相同的操作发生在students表上时,它会删除、更新和插入到speciality表中。

这是speciality表应该如何处理以下内容:

SQL> INSERT INTO STUDENTS(id, first_name, last_name, major, current_credits) values(10001, 'sam', 'ali', 'computer science', 11);

SQL>INSERT INTO STUDENTS(id, first_name, last_name, major, current_credits) values(10002, 'kevin', 'mark', 'MIS', 4);

SQL>INSERT INTO STUDENTS(id, first_name, last_name, major, current_credits) values(10003, 'robert', 'jack', 'computer science', 8);

我该如何解决这个问题? 我不知道如何连接这两个表。

我应该使用存储过程吗?

CREATE OR REPLACE TRIGGER UpdateSpeciality
after insert or delete or update on students
for each row
begin
if inserting /* this is how far i got */

像这样的事情应该这样做。 有一些假设:)

CREATE OR REPLACE TRIGGER UpdateSpeciality
after insert or delete or update on students
for each row
declare
   cursor c_spec(sMajor speciality.major%type) is
   select * from speciality
   where major = sMajor
   for update;
   r_spec c_spec%ROWTYPE;
begin
if inserting then
    open c_spec(:new.major);
    fetch c_spec into r_spec;
    if c_spec%FOUND then
        update speciality set
          total_credits = total_credits + :new.current_credits,
          total_students = total_students + 1
        where current of c_spec; 
    else
        insert into speciality(major, total_credits, total_students) values (:new.major, :new.current_credits, 1);
    end if;
    close c_spec;
elsif updating then
    open c_spec(:new.major);
    fetch c_spec into r_spec;
    if c_spec%FOUND then
        update speciality set
          total_credits = total_credits + :new.current_credits - :old.current_credits
        where current of c_spec;     
    else
        insert into speciality(major, total_credits, total_students) values (:new.major, :new.current_credits, 1);    
    end if;
    close c_spec;
elsif deleting then
    open c_spec(:old.major);
    fetch c_spec into r_spec;
    if c_spec%FOUND then
        update speciality set
          total_credits = total_credits - :old.current_credits ,
          total_students = total_students - 1
        where current of c_spec;         

        if r_spec.total_students = 1 then
            delete from speciality where major = :old.major;
        end if;
    end if;
    close c_spec;
end if;
end;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM