首页 > 解决方案 > PLSQL 游标循环

问题描述

我正在尝试使用嵌套在游标 for 循环内的 for 循环在 PLSQL 中执行趋势分析。目标是让一名演员在 2000 年至 2013 年间在 5 年内至少出演 8 部电影。

例如,期望的输出是:Wahlberg, Mark 在 2009 年到 2013 年期间出演了 10 部电影。这是我收到的错误: 在此处输入图像描述

这是我目前正在使用的代码:

DECLARE
    t movie.yr%TYPE;
    actor_id actor.id%TYPE;
    total INTEGER;
    name actor.name%TYPE;
CURSOR c_actor IS
    select *
    from (select actor.name AS name, count(movie.title) AS total
        from actor, movie, casting
        where movie.id = casting.movie_id
        and actor.id = casting.actor_id
        and movie.yr >= 2000 and movie.yr <=2013
        group by actor.name
        order by count(movie.title) DESC)
    where rownum <= 10;
BEGIN
for v_actor in c_actor
LOOP
    for t in 2000 .. 2009
    LOOP
    select name, total
    into name, total
    from actor, movie
    where movie.yr between t and t+4
    and actor_id = v_actor.actor_id
    and total >= 8
    group by name;
       dbms_output.put_line(name||' played in '||total||' movies between '||t||' and '||t+4);
   END LOOP;
END LOOP;
END;

标签: oraclefor-loopplsqlnested-loops

解决方案


看来你把它复杂化了。这应该有效:

begin
  for v_actor in (select a.name, count(*) total
                  from actor a join casting c on a.id = c.actor_id
                  join movie m on m.id = c.movie_id
                  where m.yr between 2000 and 2013
                  group by a.name
                  having count(*) >= 8
                 )
  loop
    dbms_output.put_line(v_actor.name ||' acted ' || v_actor.total ||' times');
  end loop;
end;

我认为您在几个小时前创建了一个问题(并删除了它),犯了同样的错误。例如:您创建了一个名为 的变量total,并且 - 同时 - 将它包含在游标的select语句中。您希望显示由游标获取的值,而不是变量本身,除非游标获取到该变量 - 但这是在您显式打开/从游标中获取时完成的,而不是在游标FOR循环中。有了它,您可以使用游标变量并使用它来显示这些值。


推荐阅读