PL-SQL中的触发器

时间:2019-03-30 00:47:19

标签: sql oracle plsql

我有两个表:

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的触发器,当对speciality表进行相同操作时,该触发器将删除,更新并插入students表中。

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 */

1 个答案:

答案 0 :(得分:0)

类似的事情应该可以做到。有一些假设:)

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;