【问题标题】:Counting records in a table and updating a table using a cursor计算表中的记录并使用游标更新表
【发布时间】:2015-11-21 17:22:31
【问题描述】:

我在 Oracle 中有以下表格:

Teacher
id_teacher (pk)
number_courses

Course
id_course (pk)
id_teacher (fk)

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

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;

【问题讨论】:

    标签: oracle


    【解决方案1】:

    不要使用光标。 (除非这是对您所面临的实际问题的显着简化。或者这是一个经过深思熟虑的家庭作业问题。在这种情况下,秘密是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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2011-06-18
      • 2017-05-04
      • 2016-06-10
      • 1970-01-01
      相关资源
      最近更新 更多