30

有没有办法在 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;

但是有没有更好的方法来做到这一点?定义一组值并遍历它们?

谢谢。

4

2 回答 2

50

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

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;
于 2012-05-29T11:37:27.230 回答
12

这来自 ABCade 对当前接受的答案的评论,但我发现它更干净,值得更多关注:

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;
于 2019-02-06T19:45:20.770 回答