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.
Create or replace procedure print_string( IN_string IN varchar2 ) AS v_length number(10); v_out varchar2(20); Begin v_length := length(IN_string); for i in 1.. v_length Loop v_out := substr(IN_string,i,1) ; DBMS_OUTPUT. PUT_LINE(v_out); End loop; DBMS_OUTPUT.
Write a program containing a loop that iterates from 1 to 1000 using a variable I , which is incremented each time around the loop. The program should output the value of I every hundred iterations (i.e., the output should be 100, 200, etc). Display the output on the screen using dbms_output. put_line .
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With