计算表中的记录并使用游标更新表

时间:2015-11-21 05:31:16

标签: oracle

我在Oracle中有以下表格:

Teacher
id_teacher (pk)
number_courses

Course
id_course (pk)
id_teacher (fk)

我想创建一个游标,通过计算教师被分配到的课程来更新number_courses表中的Teacher字段。据我所知,我应该先声明一个这样的游标:

cursor c_teacher IS
        select id_teacher from teacher;

然后执行for循环迭代此游标的结果并计算分配的课程,我的解决方案的草稿是:

declare
  countC number(2);
    cursor c_teacher IS
        select id_teacher from teacher;
begin
    for data in c_teacher
    loop
        select count(id_teacher) into countC from Course where id_teacher=data;
        --I can output here with a DMBS_OUTPUT only to see if its working, but
        --I need to use an UPDATE instruction
    end loop;
end;

1 个答案:

答案 0 :(得分:2)

不要使用光标。 (除非这是对你所面临的实际问题的一种戏剧性的简化。或者这是一个经过深思熟虑的作业问题。在这种情况下,秘密是update where current of

具有相关子查询的单个更新语句将完成此任务:

update Teachers T
set number_courses = (select count(*)
    from Courses C
    where C.id_teacher = T.id_teacher);

什么可能更好,因为值不能不同步,是不在教师表中存储课程数量,并在需要时计算正确的值:

alter table Teachers drop column number_courses;

create view Teachers_VW as
select T.id_teacher
    , count(*) as number_courses
from Teachers T
left outer join Courses C on C.id_teacher = T.id_teacher
group by T.id_teacher;