循环预定义的值

时间:2012-05-29 11:23:03

标签: oracle stored-procedures for-loop plsql

有没有办法在oracle中执行“for each”,如下所示:

begin
  for VAR in {1,2,5}
  loop
    dbms_output.put_line('The value: '||VAR);
  end loop;
end;

我知道你可以这样做:

begin
  for VAR in 1..5
  loop
    if VAR in(1,3,5) then
      dbms_output.put_line('The value: '||VAR);
    end if;
  end loop;
end;

但是,有没有办法以更好的方式做到这一点?定义一组值并迭代它们?

感谢。

2 个答案:

答案 0 :(得分:35)

你可以做到这一点,虽然可能不像你想的那样光滑:

declare
  type nt_type is table of number;
  nt nt_type := nt_type (1, 3, 5);
begin
  for i in 1..nt.count loop
    dbms_output.put_line(nt(i));
  end loop;
end;

如果在数据库中创建类型:

create type number_table is table of number;

然后你可以这样做:

begin
  for r in (select column_value as var from table (number_table (1, 3, 5))) loop
    dbms_output.put_line(r.var);
  end loop;
end;

答案 1 :(得分:1)

这来自A.B. Cade对currently accepted answer的评论,但我发现它更加简洁,值得更多关注:

BEGIN
  FOR i IN (SELECT column_value FROM table(sys.dbms_debug_vc2coll(1, 3, 5))) LOOP
    dbms_output.put_line(i.column_value);
  END LOOP;
END;
相关问题