33

Is there a way to do a "for each" in oracle, something like this:

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

I know you can do something like:

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;

But isn't there a way to do this in a nicer way? Defining a set of values and iterating through them?

Thanks.

Filburt
  • 17,626
  • 12
  • 64
  • 115
JGS
  • 813
  • 2
  • 8
  • 17
  • Put the list of values in a table. You can now loop through the values in the table using a cursor. – Rene May 29 '12 at 11:56

2 Answers2

52

You could do this, though probably not as slick as you'd like:

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;

If you create a type in the database:

create type number_table is table of number;

then you can do this:

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;

Also, as A.B.Cade has commented below there are database types that come with Oracle that you can use, such as sys.dbms_debug_vc2coll:

begin
  for r in (select column_value as var from table (dbms_debug_vc2coll (1, 3, 5))) loop
    dbms_output.put_line(r.var);
  end loop;
end;
Tony Andrews
  • 129,880
  • 21
  • 220
  • 259
  • 16
    Actually you don't need to create a type in the DB, you can do `for r in (select column_value from table(sys.dbms_debug_vc2coll(1,3,5))) loop` – A.B.Cade May 29 '12 at 12:01
  • @A.B.Cade - Please make this an answer so it'll get proper visibility. I'll add it as an answer myself if you don't within a few days. – ArtOfWarfare Dec 19 '18 at 21:58
14

This comes from A.B.Cade's comment on the currently accepted answer, but I find it a lot cleaner and deserving of more attention:

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;
ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193
  • 3
    Thanks. For anyone need solution for strings values: It can pass strings as parameters, too `sys.dbms_debug_vc2coll('a', 'b', 'c')` – tungns Jul 14 '20 at 08:56